tags:

views:

51

answers:

4
<script type="text/javascript">
$(function(){
    $('<h2>Click</h2>').prependTo($('#container')).live('click',function() {
        return false;
    });
    $('#container').click(function() {
        alert(1);
    });
});
</script>


<div id="container">

</div>

I don't want the click event to propagate to the #container,and that's why there is return false,but obviously it's not working

A: 

Use a parameter to your event handler. That parameter will be bound to the event object:

$('<h2>Click</h2>').prependTo($('#container')).live('click',function(e) {
    e.stopPropagation();
    return false;
});
Tom Bartel
No,I think you should see this post:http://stackoverflow.com/questions/2017755/whats-the-difference-between-e-preventdefault-and-return-false/2017761#2017761
Right, I forgot, when a `live` event is handled, it has already bubbled up to the document (I think), so stopping propagation has no effect. Thanks for the downvote, anyway.
Tom Bartel
In fact that downvote is not issued by me
Ok, sorry about that.
Tom Bartel
+2  A: 

It has to do with using the live selector and event delegation. You don't even need that live handler. Change your #container click like this:

$('<h2>Click</h2>').prependTo($('#container'));
$("#container").click(function(e){
    if(e.target.nodeName != "H2"){
       alert(1);
    }
});

Or if it looks nicer to use all jQuery:

$("#container").click(function(e){
    if($(e.target).is('h2') == false){
       alert(1);
    }
});

Both of those examples test where the original click happened, and won't execute if a H2 was clicked.

Doug Neiner
A: 

live cannot be used to a jquery object like this.

Quoting from Events/live:

Live events currently only work when used against a selector. For example, this would work: $("li a").live(...) but this would not: $("a", someElement).live(...) and neither would this: $("a").parent().live(...).

Here Be Wolves
I tried this,but still failed:$h2 = $('<h2>Click</h2>').prependTo($('#container')); $($h2,$('#container')).live('click',function() { return false; });
this, as expected, will not work. read the documentation.
Here Be Wolves
Incidentally, Jquery 1.4 now supports context for `live` - so `$('a', someElement).live ()` would actually work
K Prime
hmm, pretty recent...
Here Be Wolves
+1  A: 

You don't need live for what you're doing - use bind (or click directly) instead:

$('<h2>Click</h2>').prependTo($('#container')).click (function() {
    return false;
});

If you really meant a live-binding to h2s, you should call:

$('h2').live ('click', function () { ... });
K Prime
So it's caused by `live`?
Correct - `live` expects a jQuery selector, not a HTML fragment (as you've given above)
K Prime