我已经在下面的代码中解释了这个问题
<div id='content'>
<div id='help'>
blah blah blah
once there lived a king named midas
blah blah blah
</div>
<script>
$(document).ready(function() {
$('#help').click( function () {
$('help').hide(500);
})
})
</script>
<!-- bottom of the page after a long other content -->
</div>
<!-- end of div id= content -->
<script>
function ondelete()
{
// doing an ajax request to after deleting some items to dynamically update a list.
// the result will also have the same above div code with that help div
document.getElementById('content').innerHTML = xmlHTTP.responseText
}
</script>
在一个div里面有一个内容部分,它的id是' content‘,我有一个help div。它是display:none bydefault,如果用户单击帮助按钮,我将执行
$('#help').show(500);
当用户单击相同的帮助按钮时,或者如果用户在帮助目录中单击,则我执行此代码来隐藏该目录$('# help ').hide(500)
这一直运行良好,直到我执行ajax请求来更新div id=' content‘的内容,我正在用相同的内容覆盖相同的help div。这就像我覆盖了除了页眉和页脚之外的整个内容区域。
但是在使用响应文本更新它之后,位于document.ready内部的代码顶部的单击事件不起作用,因为onclick在该div上起作用
我的意思是它工作得很好。如果没有单击并使用上面的文档就绪代码,它在从ajax中重写时将无法工作。
根据我的经验,当使用ajax动态获取和更新带有script、src和script标记的代码时,javascript代码或链接不起作用。
现在我使用onclick而不是那个准备隐藏和显示help div的文档。
最重要的是
when there is a overwrite from ajax if you again set
$(#'help').click = .... code
this works.
like
function ondelete()
{
document.getElementById('content').innerHTML = xmlHTTP.responseText
$('#help').click (function() { $('#help').hide(500); });
}
因此,当您使用ajax更新它时,您似乎必须更新所有附加的事件。
请提出您的意见和建议,以克服这一点。
发布于 2010-07-28 15:30:14
尝试使用.live()
。
$(document).ready(function() {
$('#help').live('click', function () {
$(this).hide(500);
});
});
.live( eventType,handler )
从1.9版开始,.live()已被弃用。
然后,您可以使用http://api.jquery.com/delegate/
将处理程序附加到与当前选择器匹配的所有元素的事件中。
发布于 2010-07-28 15:32:07
尝试:
$('#help').live('click', function() {
// ...
});
而不是:
$('#help').click(function() {
// ...
});
发布于 2013-06-20 14:47:40
Live已弃用。您应该在上使用。
单击$(文档).on(“”,“选择器”,.on () {
是on的实时/委派格式。
http://api.jquery.com/live/
https://stackoverflow.com/questions/3350752
复制相似问题