我正在使用jQuery编写一个脚本,将多个控件盒(div)添加到网页中。这些div包含控件(锚点),如close,prev,next,search等。代码示例:
$div_overlay =
$('<div></div>')
.addClass('overlay')
.append($('<div></div>')
.addClass('text_controls')
//The onClick method below works perfect but not .click() of jQuery(due to the way 'index' is used)
.append($('<a onClick="overlay_hide('+index+'); return false;"></a>')
.addClass('close')
.attr('href','#')
/*.click(function(){
//The 'index' gets incremented as divs are created and hence a wrong value(the last one) is passed irrespective of the div clicked
overlay_hide(index)
})*/
)
'index'是一个全局变量,用于跟踪创建的'overlay'div。 它随着div的创建而递增,并且每个div在创建时都被推入数组中。所以,'index'基本上是div的数组索引。
为了简单起见,我只添加了“关闭”锚点。 $ div_overlay位于每次单击图像时调用的函数中。
我的问题是处理像'close'这样的锚点的点击事件。我想使用'index'来识别用于点击锚点的div,这是一个全局变量。
我希望能够传递对执行关闭操作的div的引用。如果我使用上面代码中注释的jQuery click方法来关闭div,它会将最后一个索引值作为参数传递给overlay_hide()(因为索引会随着div的创建而递增)。如果我使用上面的onClick方法,它通过传递正确的索引值工作正常。
那么,如何使用索引识别这些div并能够根据单击的div控件唯一地访问它们? (可能需要使用对象,但我不确定。)
一种方法是让点击的锚点的父节点相邻,我不希望这样做,并且想要使用索引。
答案 0 :(得分:1)
您可以使用数据属性将元数据添加到锚点。
$('<a data-index="' + index + '"></a>').click(function(){
var data = $(this).data();
overlay_hide(data.index); // note index will be a string
return false;
});
你可以做的另一种方法是使用点击功能关闭:
$('<a />').click(function(i){
return function(e){
// use i here this is the callback.
overlay_hide(i);
return false;
};
}(index));
我还想指出您添加了一个ID .attr('id','overlay')
- 并且ID在整个DOM中必须是唯一的。
答案 1 :(得分:1)
您应该阅读JS中的闭包和范围:http://bonsaiden.github.com/JavaScript-Garden/#function.closures
快速解决您的问题:
var closeButton = (function(index){
return $('<a></a>').addClass('close').attr('href','#').click(function(){
overlay_hide(index);
})
})(index);
var $div_overlay = $('<div></div>').attr('id','overlay').append(
$('<div></div>').addClass('text_controls').append(closeButton)
)
答案 2 :(得分:1)
使用容器上的“叠加”类会更容易:
$('body').delegate('a.close', 'click', function() {
$(this).closest('div.overlay').hide();
});
只需将其设置为其他类型的控件,然后您就不必担心在添加的标签中粘贴那些丑陋的DOM0处理程序。
我知道你说过“你不想这样做”,但除非你能解释为什么这样的练习一般有价值,否则建议最明显的解决问题的方法似乎是不道德的
答案 3 :(得分:0)
我认为你需要使用live()函数,请阅读: