我正在创建一堆 div
并使用一个简单的函数通过引用的 js
文件插入缩略图。基本上我试图将点击处理程序分配给循环中的每个新 div
但可能由于语法原因它不起作用。
这是我的代码(已更新)...
function makethumbs() {
for (var i = 0; i < 14; i++) {
var backgroundUrl = script_vars + "/images/gallery/thumbs/g" + (i+1) + ".jpg",
newdiv = $('<div />', {id: 'thumbnail'+i, width: 145, height: 84});
newdiv.css({display:'inline',
float:'left',
margin:'2px 2px 0 0',
color:'#000',
fontSize:'18px',
zIndex:0,
html:'P',
background: 'url(' + backgroundUrl + ')'
});
newdiv.click(function() {
$(this).stop(true, true).fadeTo('slow', 0);
});
$('#thumbholder').append(newdiv);
}
$('#arrowright').click(function() {
var L = $('#thumbholder'),
margL = parseInt(L.css('marginLeft'), 10),
newMarg = (margL - 147) + 'px',
anim = {opacity: 1};
anim["marginLeft"] = newMarg;
$('#thumbholder').stop(true, true).animate(anim, 400);
});
}
还有一个额外的点击处理程序用于#arrowright
,它工作得很好。不确定它是否是 z 排序的东西,因为可点击箭头 div
位于覆盖缩略图 div
的容器内(如果有意义的话)。
最佳答案
为什么不继续使用 jQuery?
function makethumbs() {
for (var i = 0; i < 14; i++) {
var backgroundUrl = script_vars + "/images/gallery/thumbs/g" + (i+1) + ".jpg",
newdiv = $('<div />', {id: 'thumbnail'+i, width: 145, height: 84});
newdiv.css({display:'inline',
float:'left',
margin:'2px 2px 0 0',
color:'#000',
fontSize:'18px',
zIndex:0,
html:'P',
background: 'url(' + backgroundUrl + ')'
});
newdiv.click(function() {
$(this).stop(true, true).fadeTo('slow', 0);
});
$('#thumbholder').append(newdiv);
}
$('#arrowright').click(function() {
var L = $('#thumbholder'),
margL = parseInt(L.css('marginLeft'), 10),
newMarg = (margL - 147) + 'px',
anim = {opacity: 1};
anim["marginLeft"] = newMarg;
$('#thumbholder').stop(true, true).animate(anim, 400);
});
}
因为您的主要问题是尝试将带有 jQuery 语法的点击处理程序附加到 native JS DOM 元素。
关于javascript - JQuery 点击处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13793654/