-2

I'm student and it hasn't been long since I studied programming. below code is simplified than real for explain. 'test()' is actually Ajax function to get data. My goal is making 'a tag' for paging operation. But when i clicked 'a tag', 'test()' inside of '$(document).ready' is called after 'a tag' click event occurred. So page is always back to 1. I don't know why this happen. Anyone could help me? Thank you!

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script type="text/javascript">
var page = 1;
$(document).ready(function(){
    test();
    alert(page);
});
function test(){
    for(var i = 1; i <= 3; i++) {
        var a = $("<a></a>").text(i).attr({
            href: "",
            idx: i
        });
        a.preventDefault;
        $(a).click(function(){
            page = $(this).attr("idx");
            test();
            alert(page);
        });
        $("#pageLink").append(a," ");
    }
}
</script>
</head>
<body>
hello!
<div id="pageLink"></div>
</body>
</html>
정재호
  • 3
  • 1
  • Not part of the problem but `a` is a jQuery object already, you don't need to then wrap it with $(). – Popnoodles Nov 03 '20 at 17:23
  • I solved problem. Thank you for advice about jQuery object doesn't need to wrap it with '$()'. I've not known about it. – 정재호 Nov 04 '20 at 06:46

1 Answers1

-1

For some reason you're calling test() inside of test(). There are a few minor things you need to change also

  • Prefix jQuery objects with $. var $a=... to avoid ambiguity.
  • preventDefault is used on the event, not the jQuery object. $a.click(function(event){event.preventDefault();...});

Otherwise it works as I believe you want it to, alerting the page number on click.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    createLinks();
});
function createLinks(){
    for(var i = 1; i <= 3; i++) {
        var $a = $("<a></a>").text(i).attr({
            href: "",
            idx: i
        });
       
        $a.click(function(event){
            event.preventDefault();
            page = $(this).attr("idx");
            // why are you calling this again? // test();
            // maybe you want to load something // loadSomething(page);
            alert(page);
        });
        $("#pageLink").append($a," ");
    }
}
</script>
</head>
<body>
hello!
<div id="pageLink"></div>
</body>
</html>
Popnoodles
  • 28,090
  • 2
  • 45
  • 53
  • Thank you for your kind answer!! My fault is using 'preventDefault' method to 'a tag' not 'event'. So 'href="" ' is operated and web page is refreshed and page is back to 1. I thank you again and have a nice day :) – 정재호 Nov 04 '20 at 06:44