我有几个div HTML元素,我用一个clone(true)选项克隆它,因为我也想复制事件.
现在我的HTML div块中存在某些点击事件,而在创建事件时,我也使用了context参数
var $block ="<div class='task-create-content' >"+
"<div class='task-create-preview'>"+
"<div class='items'>" +
"<div><input type='text' class='edit wtp'/></div>" +
"<div><input type='text' class='edit wtp'/></div>" +
"</div>"+
"</div>");
$(".wtp", $block).live('click',function() {
alert("hi");
})
Run Code Online (Sandbox Code Playgroud)
现在,当我使用克隆此块时clone(true),即使我正在分配上下文参数,click事件也不会触发.
该.live()方法需要实际的选择器来匹配元素。
尝试这个:
$(".task-create-content .wtp").live('click',function(){
alert("hi");
});
Run Code Online (Sandbox Code Playgroud)
它使用文档根部的选择器来查看到底收到了单击事件的内容。如果存在匹配,它将触发该选择器的处理程序。
看起来好像您直接为新创建的元素分配处理程序。如果您想这样做,请使用.bind().
$(".wtp",$block).bind('click',function(){
alert("hi");
});
Run Code Online (Sandbox Code Playgroud)
...这与执行相同:
$(".wtp",$block).click(function(){
alert("hi");
});
Run Code Online (Sandbox Code Playgroud)
编辑:
live()将事件限制为正确的几种方法$block是将$block作为第三个参数传递给live()。
$(".wtp").live('click',function(){
alert("hi");
}, $block); // The handler is placed on $block and fired for .wtp elements within
Run Code Online (Sandbox Code Playgroud)
...这与使用相同.delegate()
// The handler is placed on $block and fired for .wtp elements within
$block.delegate('.wtp', 'click', function(){
alert("hi");
});
Run Code Online (Sandbox Code Playgroud)
jQuery.delegate()只是更好地将第三个参数传递给.live(). 它只是重新排序参数,并调用.live().
http://github.com/jquery/jquery/blob/master/src/event.js#L875
| 归档时间: |
|
| 查看次数: |
1145 次 |
| 最近记录: |