我对此很陌生,所以请耐心等待......
假设我有这段 JavaScript 代码
$(document).ready(function() {
$("a").click(function() {
alert("Hello world!");
});
});
按照我的理解,这段代码将“捕获”任何链接选择并发布一个警报框。通常这工作得很好。
现在,在同一页面上我还有一个表,在提交时,我捕获表单提交并使用 JQuery 将行添加到用户显示,同时将数据发送到服务器。
这里是拦截post请求的代码(大部分取自Railscasts #136)
jQuery.ajaxSetup({
'beforeSend': function(xhr) {
xhr.setRequestHeader("Accept", "text/javascript")
}
})
jQuery.fn.submitWithAjax = function() {
this.submit(function() {
$.post(this.action, $(this).serialize(), null, "script");
return false;
})
return this;
};
$(document).ready(function() {
$("#new_ride_form").submitWithAjax();
})
这是渲染部分的代码...
$("#add_new_ride").before("<%= escape_javascript(render(:partial => @ride)) %>");
$("#ride_<%<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c5f885b7aca1a0ebaca1" rel="noreferrer noopener nofollow">[email protected]</a> %>").effect("highlight", {color: '#aaffaa'}, 2000);
$("#new_ride_form")[0].reset();
这是在部分生成的表格单元格之一中创建链接的代码
<td><%= link_to 'remove', ride_url(ride),
:id => :destroy_ride,
:method => :delete,
:href => delete_ride_url(ride) %>
</td>
现在,当我提交表单,然后单击新创建的表行中的“删除”链接时,它只是提交删除请求。用于创建“Hello World”警报框的 JavaScript 未执行。
但是,如果我提交表单,创建新的表格行,然后手动刷新页面,然后单击新创建的表格行中的“删除”链接,即“Hello World”警报框按预期出现。
在获得预期行为之前我需要手动刷新,这是怎么回事?
在使用 AJAX 添加表行后是否需要触发“document.ready”事件或其他事件,以便告诉代码“嘿,这里有一些新内容需要注意”。
谢谢!
顺便说一句,我正在使用 Rails 和 JQuery 进行编码,但我不确定这是否重要。
最佳答案
听起来您想使用 jQuery.live
而不是 jQuery.click
。不同的是jQuery.click
将为所有当前绑定(bind)点击事件<a>
元素,以及jQuery.live
将绑定(bind)所有当前和 future 元素。
$(document).ready(function() {
$("a").live("click", function() {
alert("Hello world!");
});
});
关于jquery - AJAX 不是 "capturing"事件没有刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1213264/