Reputation: 11165
I have this html tags that I criated with a click event.
After this via jquery I am adding to it dynamically another tag (span).
I want that the span will not execute the alert, how?
(if I click on the "I am new Text" - I want nothing to happened )
you can test it here: http://jsfiddle.net/r97AT/16/
what I did here not working:
<b onclick="alert('q1')" id="q1" class="test">test</b>
<br>
<b onclick="alert('q2')" id="q2" class="test">test</b>
<br>
<b onclick="alert('q3')" id="q3" class="test">test</b>
$(document).ready(function () {
$(".test").each(function () {
$(this).append(function () {
return $('<span id="newChild_'+$(this).attr('id')+'" style="color:red"> I am new Text</div>');
});
$('#newChild_' + $(this).attr('id')).live('click', function (e) {
e.stopPropagation();
});
});
});
Upvotes: 3
Views: 1560
Reputation: 69915
live
uses event bubbling mechanism and attached event handler on the document body object. Even if you try to stop the event propagation in live
handler it is not going to work because right after event target there is b
tag which is listening to this event. You can try to use bind
after dynamically adding the markup.
Take a look at this working demo
$(document).ready(function () {
$(".test").each(function () {
$(this).append(function () {
return $('<span id="newChild_'+$(this).attr('id')+'" style="color:red"> I am new Text</div>');
});
$('#newChild_' + $(this).attr('id')).bind('click', function (e) {
e.stopPropagation();
});
});
});
Upvotes: 2
Reputation: 19081
Try this:
$(document).ready(function () {
$(".test").each(function () {
$(this).append( $('<span id="newChild_'+$(this).attr('id')+'" style="color:red"> I am new Text</div>').bind('click', function (e) {
e.stopPropagation();
}) );
});
});
Upvotes: 2
Reputation: 3212
Live adds a listener to the document, and checks whether any event registered there matches the selector you've put in. But you onclick is at the element itself, so it's executed before the clicklistener. (this is documented on the live-page of jQuery too).
Btw, in jQuery 1.4 it's better to use delegate.
Upvotes: 0