我正在使用JQuery动态创建一些缩略图,就像这样(在循环中):
var thumb = $('<a class="tinythumb"></a>');
thumb.append('<img src="' + productThumbnailList[i] + '" width="70" height="70" />');
thumbContainer.append(thumb);
现在我正试图通过JQuery的.click()
为这些添加一些功能,但我无法让它工作。我以前从来没有遇到过这样做的麻烦,没有任何错误,从我的观点来看,我看不到任何错误。
我尝试了这个简单的.each()
来看看会发生什么。有趣的是,rel
属性 正在更新,但仍然没有.click()
功能(警报从未执行过)。
$("div#thumbcontainer a").each(function()
{
$(this).attr("rel", "works");
$(this).click(function()
{
alert('never called');
});
});
这是我正在尝试使用的页面:
http://burwell.businesscatalyst.com/catalogue/containmentscreen/Enviroguard#
以下是整个JavaScript,它可能与上面缺少相关内容:
// Properties
var thumbContainer = $("div#thumbcontainer");
var str = thumbContainer.html();
var productThumbnailList = str.split(';');
// Clear thumbContainer of junk HTML
thumbContainer.html("");
// Create thumbnails
if(productThumbnailList.length > 1)
{
for(var i = 0; i<productThumbnailList.length; i++)
{
var large = Math.round(i/2) * 2 == i ? false : true;
// create thumbnail
if(!large)
{
var thumb = $('<a class="tinythumb"></a>');
thumb.append('<img src="' + productThumbnailList[i] + '" width="70" height="70" />');
thumbContainer.append(thumb);
}
}
$("div#thumbcontainer a").each(function()
{
$(this).attr("rel", "works");
$(this).click(function()
{
alert('never called');
});
});
}
将onclick="someFunc()"
参数添加到<a>
标记会使其调用该函数。
答案 0 :(得分:1)
你没有必要在each
循环中附加点击处理程序try delegate(在循环之外)
$("div#thumbcontainer").delegate("a","click",function(e){
alert('never called'); /should be called
});
答案 1 :(得分:0)
由于您是动态创建锚标记,因此请使用“on”附加单击事件处理程序
$('#thumbContainer').on("click","a", function(){
alert("will work now");
});
如果您使用的是旧版本的jquery,请使用live()或delegate()。
答案 2 :(得分:0)
代码添加中存在语法错误)到代码结尾
$("div#thumbcontainer a").each(function()
{
$(this).attr("rel", "works");
$(this).click(function()
{
alert('never called');
});
})
答案 3 :(得分:0)
使用jQuery处理delegated events的正确方法是使用.on
。基本上,当您动态添加元素时,它们在绑定处理程序时实际上还不存在。因此,您将函数绑定到新的静态祖先元素 - 当您绑定处理程序时, 存在的一个元素,并让事件'冒泡',并在那里处理它。 / p>
代码方面,这就是你最终要做的事情:
摆脱所有这些。
$("div#thumbcontainer a").each(function()
{
$(this).attr("rel", "works");
$(this).click(function()
{
alert('never called');
});
});
将其替换为此。
// $('#thumbcontainer a').attr('rel', 'works'); chain this directly if needed
$("#thumbcontainer").on('click', 'a', function(e)
{
e.preventDefault(); // prevent the click from following link
alert('this gets called!');
});