jQuery - 似乎无法 .live() 绑定到标签元素。为什么?
这是我的代码:
HTML:
<ul id="more-items">
<li><label class="button">hi</label></li>
<li><label class="button">hi</label></li>
<li><label class="button">hi</label></li>
</ul>
Javascript:
$('ul#more-items label.button').live('click', function()
{
alert(1);
});
单击标签不会导致alert() 触发。 .live() 绑定似乎对标签元素没有影响...
如果我将其更改为使用 .click() 甚至 .bind(),它会完美地工作。 .live() 不起作用有什么原因吗?有办法解决这个问题吗?
我使用 .live() 的原因是因为 ul#more-items
将被多次读取到页面,我不想每次发生这种情况时都必须触发一个函数重新绑定点击。
Here's my code:
HTML:
<ul id="more-items">
<li><label class="button">hi</label></li>
<li><label class="button">hi</label></li>
<li><label class="button">hi</label></li>
</ul>
Javascript:
$('ul#more-items label.button').live('click', function()
{
alert(1);
});
Clicking on the labels doesn't cause the alert() to fire. The .live() bind seems to have no affect on the label element...
If I change it to use .click() or even .bind(), it works perfectly.
Is there any reason why .live() isn't working? Is there a way to fix this?
The reason I'm using .live() is because ul#more-items
will be readded to the page multiple times and I don't want to have to fire off a function each time that happens to rebind the click.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
jQuery 的
live()
方法依赖于事件冒泡(一直到根节点)来工作。如果有任何代码会停止
label
或其任何祖先上的事件冒泡,则live()
将不起作用。label
或其祖先之一是否有可能具有具有以下任一功能的处理程序?或者
如果是这样,
live()
将失败。相关 jQuery 文档:
.live()
- http:// /api.jquery.com/live/.stopPropagation()
- http://api.jquery.com/event.stopPropagation/jQuery's
live()
method relies on event bubbling (all the way up to the root node) to work.If there's any code that will stop the bubbling of the event on either the
label
or any of its ancestors,live()
will not work.Any chance that the
label
or one of its ancestors has a handler with either of the following?or
If so,
live()
will fail.Relevant jQuery docs:
.live()
- http://api.jquery.com/live/.stopPropagation()
- http://api.jquery.com/event.stopPropagation/元素 id 必须是唯一的。你的陈述“我使用 .live() 的原因是因为 ul#more-items 将被多次读取到页面..”告诉我你将有多个这样的内容:
这将是无效的 HTML,因为 ID 更多- 项目存在两次。
Element ids must be unique. Your stament "The reason I'm using .live() is because ul#more-items will be readded to the page multiple times.. " tells me that you will have multiple of these:
This would be invalid HTML as the ID more-items exists twice.
尝试
或
try
or
看起来没问题,但你的警报应该是alert("1");
或者:
var 1=“1”;
警报(1);
It seems ok, but your alert should be alert("1");
or:
var 1="1";
alert(1);
你可以试试这个。它可能会起作用
更改:
到此:
You can try this. It may work
Change:
To This:
你的代码对我有用。你使用什么版本的jquery?您是否在 $(document).ready 函数中定义了 javascript?
Your code works for me. What version of jquery are you using? Are you defining the javascript in a $(document).ready function?