当附加了 li 后,它不会“真正”成为 ul 的一部分吗?
我现在有这段代码:
<ul><li class="listitem">text<li></ul>
jQuery:
$('.listitem').click(function() {
$("#elname").text($(this).text());
$('#slists').css('visibility','hidden')
$('#elname').css('visibility','visible')
$('#elname').css('display','inline-block')
});
This is Should to hide a div 并且确实如此,但是当我将项目附加到 ul (使用类 listitem)时,附加项目没有任何反应,它获得的类是正确的,标题,以及价值。
这可能与上面的代码在文档就绪函数中执行的操作有关吗?
I have right now this code:
<ul><li class="listitem">text<li></ul>
jQuery:
$('.listitem').click(function() {
$("#elname").text($(this).text());
$('#slists').css('visibility','hidden')
$('#elname').css('visibility','visible')
$('#elname').css('display','inline-block')
});
This is supposed to hide a div and it does, but when I append items to the ul (with the class listitem) nothing happens with the appended item, the class it gets is correct, the title, and the value too.
Can this have something to do with the code above being in the document ready function to do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
.live()
代替,如下所示:。 live()
在document
级别侦听您的点击以冒泡...并且新元素和旧元素以相同的方式冒泡此事件,因此它不关心稍后添加的内容,其中.click()
处理程序将单击绑定到运行选择器时存在的元素。或者,您可以为
提供 ID 或类,并使用
.delegate()
像这样:这会减少冒泡,因此在事件方面更加整洁,它在
处捕获它,而不是一直到
文档
。Use
.live()
instead, like this:.live()
listens at thedocument
level for your click to bubble up...and new and old elements bubble this event the same way, so it doesn't care what was added later, where as your.click()
handler binds a click to elements that existed at the time the selector was run.Alternatively, you can give your
<ul>
an ID or class and use.delegate()
like this:This results in less bubbling, so just a bit neater on the event side, it captures it at the
<ul>
instead of all the way up ondocument
.单击事件在设置时在 DOM 中的所有元素上设置一次。添加列表项不会重新生成这些点击项。
您需要使用 jQuery 的 实时事件功能 来创建应用于在以下位置创建的元素的点击事件:苍蝇。
Click events are set once on all elements in the DOM at the time of setting. Adding a list item won't regenerate these click items.
You'll need to use jQuery's live event functionality to create click events that apply to elements created on-the-fly.