jQuery - Can't seem to .live() bind to a label element. Why?
Here's my code:
HTML:
<ul id="more-items">
<li><label class="button">hi</label></li>
<li><label class="button">hi</label>&l开发者_运维百科t;/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.
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?
return false;
or
event.stopPropagation();
If so, live()
will fail.
Relevant jQuery docs:
.live()
- http://api.jquery.com/live/.stopPropagation()
- http://api.jquery.com/event.stopPropagation/
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:
<ul id="more-items">
<!--Stuff-->
</ul>
<ul id="more-items">
<!--Stuff-->
</ul>
This would be invalid HTML as the ID more-items exists twice.
try
$('label.button').live('click', function()
{
alert(1);
});
or
$('ul#more-items').delegate('label.button','click', function()
{
alert(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:
$('ul#more-items label.button').live('click', function()
{
alert(1);
});
To This:
$('ul#more-items label.button').unbind('click').live('click', function()
{
alert(1);
});
Your code works for me. What version of jquery are you using? Are you defining the javascript in a $(document).ready function?
精彩评论