很抱歉标题的问题;我想不出一个简洁的方式来表达我的问题。我有一个小的JQuery脚本,它执行两个AJAX调用(检索一些任意的xml)。我的问题是许多其他人似乎都有过的问题,但代码要简单得多。根据我所读到的,我的问题是JQuery“单击”侦听器和其他进程之间的竞争条件。我尝试将代码拆分为两个单独的脚本,并使用"click“侦听器”推迟“一个脚本(并调用HTML主体底部的延迟脚本)。代码是:
function extractThread(){
var xmlSource;
xmlSource = $(this).attr("id");
xmlSource = "xml/" + xmlSource;
$.ajax({ type: "GET", url: xmlSource, cache: false, success: function(data) {
setUpThread(data);
}
});
}
pub.setup = function() {
var target, thread, posts;
target = $("#threadList");
$.ajax({ type: "GET", url: "xml/forum.xml", cache: false, success: function(data) {
$(target).append("<ul></ul>");
$(data).find("thread").each(function () {
thread = $(this).find("title")[0].textContent;
posts = $(this).find("posts")[0].textContent;
$(target).find("ul").append("<li><a href=\"#\" class=\"threadName\" id=\""+ posts +"\">" + thread + "</a>");
});
}
});
/* works if: alert(anyMsg); */
$(".threadName").click(extractThread);
};/*end setup*/
return pub;
}());
$(document).ready(GetThreads.setup);
其中extractThread调用一些其他的任意方法。我不明白为什么这里会有冲突;ajax不是已经成功了吗?我已经阅读了许多与我的问题相同的问题,但我还没有能够应用所给出的建议(可能是因为现在是早上7点,我已经起床太久了)。一般的共识似乎是“添加alert()使我的代码工作”表明某些异步事件的计时存在问题……这是我第一次在StackOverflow (或任何编程板)上发帖,总的来说,我对JavaScript非常陌生,所以如果有任何我可以做的事情来澄清我的问题,或者任何人有任何关于清理我的代码的建议,我将非常感谢。干杯萨姆。注意:“远不复杂”指的是我的代码,而不是别人的代码!
编辑:(因为我不知道如何"+1",或者将问题标记为已解决):谢谢你的回复;我从来没有想过会有这么快的反应。Artem提供的:$(document).on("click",".threadName",extractThread);解决方案运行良好,谢谢!
发布于 2013-08-20 03:18:50
在下面尝试一下。Ajax是异步的,因此您只能在Ajax返回后调用该click
。因此,通过将它放在success
回调中,它将只在那时运行,而不是在此之前任意运行。发出警告会停止代码执行,因此通常会为Ajax调用提供足够的时间来成功返回。
希望这能有所帮助。
R.
function extractThread() {
var xmlSource;
xmlSource = $(this).attr("id");
xmlSource = "xml/" + xmlSource;
$.ajax({
type: "GET",
url: xmlSource,
cache: false,
success: function (data) {
setUpThread(data);
}
});
}
pub.setup = function () {
var target, thread, posts;
target = $("#threadList");
$.ajax({
type: "GET",
url: "xml/forum.xml",
cache: false,
success: function (data) {
$(target).append("<ul></ul>");
$(data).find("thread").each(function () {
thread = $(this).find("title")[0].textContent;
posts = $(this).find("posts")[0].textContent;
$(target).find("ul").append("<li><a href=\"#\" class=\"threadName\" id=\"" + posts + "\">" + thread + "</a>");
});
/* works if: alert(anyMsg); */
$(".threadName").click(extractThread);
}
});
}; /*end setup*/
return pub;
}());
$(document).ready(GetThreads.setup);
发布于 2013-08-20 03:27:19
正如@rob-schmuecker已经解释过的,Ajax是异步的,所以很可能在你附加点击事件监听器的时候,你还没有创建任何带有treadName类的锚点。
但您可以附加另一种类型的单击侦听器,该侦听器将适用于即使在添加侦听器之后仍创建的节点:
$(document).on("click", ".threadName", extractThread);
https://stackoverflow.com/questions/18321250
复制相似问题