I am trying to detect an event in a jQuery appended element.
- How do you do 开发者_如何学编程this,
- and/or why isn't this working:
Here's a simplified snippet of what I've tried. The input field fires after clicking "click me." After clicking on the input, the alert isn't firing - other events on this appended input don't fire either. :-(
The following's in script tags:
$(document).ready(function(){
$(".clickme").click(function(){$(".extra").append('write: <input type="text" class="writesomething" />');});
$("input").click(function(){alert("clicked")});
});
The following's in the body:
<a href="#" onclick="return false" class="clickme">click me</a>
<div class="extra"></div>
Do it like this:
Try it out: http://jsfiddle.net/eDDeZ/1/
$(".clickme").click(function(){
$('<input type="text" class="writesomething" />')
.click(function(){alert("clicked")})
.appendTo('.extra')
.before('write: ');
});
You're creating the new element, assigning the click handler directly to it, appending it to .extra
, then adding the write:
text before it.
No need for .live()
this way.
EDIT:
Another option is to use .delegate()
which will be more efficient that .live()
since it is focused on a particular container instead of the entire page.
Try it out: http://jsfiddle.net/eDDeZ/2/
$(".clickme").click(function(){
$('.extra').append('write: <input type="text" class="writesomething" />')
});
$('.extra').delegate('input','click',function(){alert("clicked")});
- http://api.jquery.com/delegate/
The binding of the second event handler occurs when the DOM is loaded - and no matching element exists. When you click the link, an element is added but no event handler is attached to it.
There are three ways to solve this:
Use the
.live()
api instead of.click()
$('input').live('click', function() { alert('clicked'); });
Add the event handler in the click event.
$(document).ready(function(){ $(".clickme").click(function() { $(".extra").append('write: <input type="text" class="writesomething" />'); $("input").click(function(){ alert("clicked") }); }); });
Or, similar, but making use of jQuery chaining
$(document).ready(function() { $('.clickme').click(function() { $('<input>') .attr('type','text') .addClass('writesomething') .click(function() { alert('clicked!'); }) .appendTo('.extra'); }); });
use the method live to dynamically bind events with elements instead of using bind.
For example :
$("input").live('click',function(){alert("clicked")});
精彩评论