能不能通过类名来调用使用jquery函数
for(var i=0;i<5;i++){
$(".questions").append("<a href='#' **`class='jump'`** style='margin-left:3px;' id='"+qData[i].id+"'>"+qData[i].id+"</a>");
}
$(".jump").on("click",function(){
alert("hey");
i = $(this).attr('id');
alert(i);
ourRequest = new XMLHttpRequest();
ourRequest.open("GET", "http://localhost/project/php/Chapter.php/?id="+i);
ourRequest.onload = function(){
ourData = JSON.parse(ourRequest.responseText);
$("#qqq").html(ourData[0].question);
$("#op1").html(ourData[0].first);
$("#op2").html(ourData[0].second);
$("#op3").html(ourData[0].third);
$("#op4").html(ourData[0].fourth);
};
ourRequest.send();
i++;
});
我附上链接与类名“跳”在一个div并号召类“跳”,但功能的onclick功能不运行。能不能通过类名来调用使用jquery函数
请像下面一样绑定事件。这是技术将事件绑定到DOM中运行时添加的元素或任何事件。我们可以将事件委托给所需的未来元素。即将来添加到DOM中的元素。
$("body").on("click",".jump",function(){//change $("body").on("click",".jump"
// you can also use $(document).on("click",".jump"
alert("hey");
i = $(this).attr('id');
alert(i);
ourRequest = new XMLHttpRequest();
ourRequest.open("GET", "http://localhost/project/php/Chapter.php/?id="+i);
ourRequest.onload = function(){
ourData = JSON.parse(ourRequest.responseText);
$("#qqq").html(ourData[0].question);
$("#op1").html(ourData[0].first);
$("#op2").html(ourData[0].second);
$("#op3").html(ourData[0].third);
$("#op4").html(ourData[0].fourth);
};
ourRequest.send();
i++;
});
工作很好。谢谢 –
如果这有帮助,请将其标记为答案。和一票 –
这是因为,要附加链接,DOM和当你已经定义的函数它一定到其在那里的Dom被加载时的元素。
所以你必须在jQuery中使用event delegation。
使用这样的代码:
$(document).on("click",".jump"function(){
它工作正常。谢谢 –
@DeepakJain不客气。请标记答案是正确的。谢谢 –
我应该这样** **吗? –
@Jonasw。我认为OP认为要大胆。 ;) – Shiladitya