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>