3
<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

user198729
  • 61,774
  • 108
  • 250
  • 348

4 Answers4

3

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
  • 65,509
  • 13
  • 109
  • 118
1

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
  • 5,809
  • 1
  • 25
  • 19
0

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
  • 2,283
  • 1
  • 15
  • 18
  • 1
    No,I think you should see this post:http://stackoverflow.com/questions/2017755/whats-the-difference-between-e-preventdefault-and-return-false/2017761#2017761 – user198729 Jan 15 '10 at 08:47
  • 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 Jan 15 '10 at 08:57
0

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(...).

jrharshath
  • 25,975
  • 33
  • 97
  • 127
  • I tried this,but still failed: $h2 = $('

    Click

    ').prependTo($('#container')); $($h2,$('#container')).live('click',function() { return false; });
    – user198729 Jan 15 '10 at 08:51
  • Incidentally, Jquery 1.4 now supports context for `live` - so `$('a', someElement).live ()` would actually work – K Prime Jan 15 '10 at 08:57