当用户单击名为“winners”的表时,我的 jquery 代码片段出现问题。代码
$('#winners tr').click(function() {
alert(223);
});
仅当我在此代码片段之前放置警报时才会触发,如下所示:
alert(1);
$('#winners tr').click(function() {
alert(223);
});
完整代码如下所示。问题出在底部的代码片段。
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("jquery", "1.7.1");
function listen(last_modified, etag) {
$.ajax({
'beforeSend': function(xhr) {
xhr.setRequestHeader("If-None-Match", etag);
xhr.setRequestHeader("If-Modified-Since", last_modified);
},
url: '/test/sub',
dataType: 'text',
type: 'get',
cache: 'false',
success: function(data, textStatus, xhr) {
/*REMOVED CODE*/
});
/* Start the next long poll. */
listen(last_modified, etag);
},
error: function(xhr, textStatus, errorThrown)
{
//$('#data').prepend(textStatus + ' | ' + errorThrown);
}
});
};
google.setOnLoadCallback(function() {
/* Start the first long poll. */
/* setTimeout is required to let the browser know
the page is finished loading. */
setTimeout(function() {
listen('Thu, 1 Jan 1970 00:00:00 GMT', '0');
}, 500);
});
//alert(1);
$('#winners tr').click(function() {
alert(223);
});
</script>
感谢您的帮助!
最佳答案
问题是您的代码在元素出现在 DOM 中之前执行,因此 $('#winners tr')
为空,除非您有此警报阻止脚本。
通常的解决方案是将整个 script
元素放在 body
元素的末尾,而不是放在 head
内部。或者您可以将代码包装在 jquery 就绪事件处理程序中。
当您使用 Google Load 时,最好的方法是将点击绑定(bind)代码移至您传递给 google.setOnLoadCallback
的回调中。
关于javascript - 必须在事件触发之前写入警报,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23066886/