晚上,
我有点困惑为什么我的一些 jquery 不工作。
这是一个示例证明: http://jsfiddle.net/FS34t/624/
如您所见,单击“框”会触发该警报。
但是,当我尝试在自己的代码中实现相同的行为时,单击“框”将不会触发。
function scroll(e) {
if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) {
var $items = $(balls());
$items.imagesLoaded(function(){
$container
.masonry('reloadItems')
.append( $items ).masonry( 'appended', $items, true );
});
}
}
function balls(){
$iterator -= 1;
if($iterator < 0){
var $boxes = $( '<div class="box">No more games!</div>' );
$container.append( $boxes ).masonry( 'appended', $boxes, false );
return;
}
var $width = 9;
return (
'<div class="box" style="width:18%">'
+'<p>'+$test[$iterator][1][2]['name']+'</p>'
+'<img src="scripts/php/timthumb.php?src='+$test[$iterator][2]+'&q=100&w=300"/>' //Replace this with the one below when timthumb is whitelisted
+'<div id=boxBottom>'+Math.floor($test[$iterator][0]*100)+'%</div>'
+'</div>'
);
我不确定为什么
$(".box").click(function(event){
alert("TEST");
});
在这里不起作用。 我唯一的猜测是,这是因为在 jsfiddle 示例中,“框”是在 HTML 中声明的,而这些框是在 .js 中生成的?
最佳答案
如果您运行此代码:
$(".box").click(function(event){
alert("TEST");
});
在 .box
元素被创建并插入 DOM 之前,不会安装任何事件处理程序,因为 $(".box")
在 DOM 中找不到对象运行代码时安装处理程序的 DOM(生成空 jQuery 对象)。
您有两种选择来纠正此问题:
您可以切换为使用委托(delegate)事件处理,以便将来创建的对象能够响应事件。
您可以在创建给定的
.box
元素后安装事件处理程序。
委托(delegate)事件处理(在 jQuery 1.7+ 中)将像这样工作:
$container.on("click", ".box", function(event){
alert("TEST");
});
这会将事件处理程序附加到 $container 对象(该对象在创建球之前就已经存在),然后监视源自 .box
对象的冒泡事件。
对于 jQuery 1.7 之前的 jQuery 版本,您可以使用 .delegate()
。
关于javascript - jquery 未选择预期的 div 元素。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11424903/