I am trying to add an element to the DOM, and then working with this element, once clicked. However, I dont think the function below registers because this is a self invoking function (located at the end of the HTML), and is run only at the begging.
(function (){
$('body').append('<span class="test">test</span>');
})
$('.test').click(function(){
console.log(this);
});
})();
the click event handler is not working.
thanks
Since you're element is dynamically appended you can use on()
or chain the click()
event.
//Using on()
$('body').on('click', '.test', function(){
// Bla
});
//Chaining click()
$('<span class="test">test</span>').click(function(){
// Bla
}).appendTo('body');
or you can do this,
$(function() {
$('body').append('<span class="test">test</span>');
$('.test').click(function() {
console.log(this);
});
});
though live
or on
would be the better alternative if you don't know in advance when that element is going to get added to the DOM.
Change this -
$('.test').click(function()
{
console.log(this);
});
to this -
$('.test').live('click', function()
{
console.log(this);
});
live documentation.
EDIT
As of jquery 1.7, live
has been deprecated. Use on
instead -
$('body').on('click', '.test', function()
{
console.log(this);
});
on documentation.
jsFiddle demo.
Remember, if you want to bind event handlers to dynamically generated DOM elements then you need to use either live
(deprecated) or on
.
In your example code you are the closing the wrapper function after the span is added to the body, if you remove the })
line, your code should work just fine:
(function (){
$('body').append('<span class="test">test</span>');
// }) <- remove this line
$('.test').click(function(){
console.log(this);
});
})();
As other people have already answered with, you can chain in jQuery so you would be able to do any of these to get the same result:
function someFunction() {
console.log(this);
}
// work from the span and attach a direct handler
$('<span class="test">test</span>').on('click', someFunction).appendTo('body');
// work from the body attaching direct handlers
$('body')
.append('<span class="test">test</span>')
.find('.test')
.on('click', someFunction);
// work from the body attaching a delegate handler
$('body')
.append('<span class="test">test</span>')
.on('click', '.test', someFunction);
You were closing the function just after the append part thats why click handler wasn't working
$(function() {
$('body').append('<span class="test">test</span>');
$('.test').click(function() {
console.log(this);
});
})();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.