亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

請教jquery函數操作

請教jquery函數操作

慕桂英4014372 2023-07-06 11:02:50
我是一名學生,我學習編程不久。下面的代碼比實際代碼簡化了以供解釋。'test()'實際上是獲取數據的Ajax函數。我的目標是為分頁操作制作“標簽”。但是當我單擊“a tag”時,“$(document).ready”內部的“test()”在“a tag”點擊事件發生后被調用。所以頁面總是回到1。我不知道為什么會發生這種情況。有人可以幫助我嗎?謝謝你!<!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>
查看完整描述

1 回答

?
慕桂英3389331

TA貢獻2036條經驗 獲得超8個贊

由于某種原因,您在 test() 內部調用 test() 。您還需要更改一些小事情

  • jQuery 對象帶有 $ 前綴。var $a=...以避免歧義。

  • PreventDefault用于事件,而不是 jQuery 對象。$a.click(function(event){event.preventDefault();...});

否則它會按我相信您想要的方式工作,在單擊時提醒頁碼。

<!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>


查看完整回答
反對 回復 2023-07-06
  • 1 回答
  • 0 關注
  • 113 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號