$(function(){ $('

Click

').prependTo($('#container')).live('click',...">

How to stop the spread of the event?

<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 do not want the event to clickextend to #container, and why it exists return false, but obviously it does not work

+3
source share
4 answers

This is due to the use of selector liveand delegation of events. You do not even need this handler live. Change your #containerclick as follows:

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

Or, if it's better to use all jQuery:

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

Both of these examples check where the initial click occurred, and will not run if H2 was pressed.

+3
source

You do not need livefor what you do - use bind(or click) instead :

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

h2 s, :

$('h2').live ('click', function () { ... });
+1

Use the parameter for the event handler. This parameter will be bound to the event object:

$('<h2>Click</h2>').prependTo($('#container')).live('click',function(e) {
    e.stopPropagation();
    return false;
});
0
source

live cannot be used for jquery objects like this.

Quote from Events / live :

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

0
source

Source: https://habr.com/ru/post/1728585/


All Articles