【发布时间】:2015-06-01 18:49:29
【问题描述】:
我在AJAX成功函数上做了三个链接。当用户在该页面上时,我希望每次单击这些链接中的任何一个时都运行一个 JavaScript 函数。我知道这很容易,但我无法在每次点击时运行脚本。它仅在单击第一个链接时运行,而在单击其他链接时不执行任何操作。代码如下:
request.success(function(data) {
//Put the heading on the div
//http://stackoverflow.com/questions/12898475/using-jquery-to-replace-text-inside-h3-header
var dataReceived = null;
$("#bookList h3 #spanId").text("A list appears");
for(var i=0;i<data.length;i++){
dataReceived =data[i].name;
$("#bookList").append("<a href id=bookLink>"+dataReceived+"</a>" +"<br>");
}
$("#bookLink").click(function(event){
$.getScript("information.js",function(){
dealWithData();
});
});
});
request.fail(function(jqXHR, status, errorMessage) {
if((errorMessage = $.trim(errorMessage)) === "") {
alert("An unspecified error occurred. Check the server error log for details.");
}
else {
alert("An error occurred: " + errorMessage);
}
});
dealWithData 现在只有一个警报:
function dealWithData(){
alert("Reached here");
}
感谢任何帮助。谢谢。
【问题讨论】:
-
停止使用重复的 ID。它们必须是唯一的。改用一个类。
-
从外观上看,您似乎添加了多个带有 id="bookLink" id 的标签必须是唯一的,并且它可能只命中第一个与此 id 匹配的标签,并且失败打别人,导致你的问题 $("#bookList").append(""+dataReceived+"" +"
");和 $(".bookLink").click(function(event){ 应该注意这一点
标签: javascript jquery ajax