[英]click event not firing on newly created list item
I have two lists and when you click on the second list the first list removes the first item and add to the second list but when I click on the newly created list item it doesn't fire why is that. 我有两个列表,当您单击第二个列表时,第一个列表会删除第一个项目并添加到第二个列表中,但是当我单击新创建的列表项目时,它并不会触发为什么。 jsFiddle demo
jsFiddle演示
$('#SearchList li a').bind("click", function () {
var $this = $(this).unwrap('<a href="#"></a>').remove().text();
var $that = $('#Search li:first').remove().text();
$('<li>' + $this + '</li>').insertBefore('#Search li:first')
$('#SearchList').append('<li><a href="#">' + $that + '</a></li>');
});
<ul id="Search">
<li>Electronics</li>
<li>Image</li>
</ul>
<ul id="SearchList">
<li><a href="#">Interests</a></li>
<li><a href="#">Entertainment</a></li>
<li><a href="#">Clothing</a></li>
<li><a href="#">Pharmacy</a></li>
<li><a href="#">Home & Garden</a></li>
</ul>
.bind()
only affects elements already in the DOM, you want to use .delegate()
or .on()
(if you are using jQuery 1.7+): .bind()
仅影响DOM中已经存在的元素,您想使用.delegate()
或.on()
(如果使用的是jQuery 1.7+):
$('#SearchList').on("click", " li a", function () {
var $this = $(this).unwrap('<a href="#"></a>').remove().text();
var $that = $('#Search li:first').remove().text();
$('<li>' + $this + '</li>').insertBefore('#Search li:first')
$('#SearchList').append('<li><a href="#">' + $that + '</a></li>');
});
Note: .live()
has been depreciated as of jQuery 1.7, so it's a good idea to either use .on()
or .delegate()
. 注意:
.live()
从jQuery 1.7开始已弃用,因此最好使用.on()
或.delegate()
。
Here is a jsfiddle of the above solution (using jQuery 1.7): http://jsfiddle.net/jasper/pgwdv/ 这是上述解决方案的jsfiddle(使用jQuery 1.7): http : //jsfiddle.net/jasper/pgwdv/
Some documentation links: 一些文档链接:
.on()
: http://api.jquery.com/on .on()
: http : .on()
.delegate()
: http://api.jquery.com/delegate .delegate()
: http : .delegate()
您应该尝试使用.live而不是.bind。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.