开发者

Why I can't click on this div?

When I click on the x inside of the close div, I want the background to change to white.

This is the markup:

<div class="list-item list-item-active">
    <div class="close">x</div>
</div>

This is the javascript:

$(document).ready(function(){
    $('.list-item').live('click', function() {
        if (!$(this).hasClass('list-item-active'))
            $(this).addClass('list-item-active');
    });
    $('.list-item .close').live('click', function() {
        $(this).parent().removeClass('list-item-active');
    });
});

This is the css:

.list-item {width:100px;height:100px;bac开发者_StackOverflow社区kground:#fff}
.list-item-active {background:#ccc}

Demo: http://jsfiddle.net/JMeff/


You can click it, but the click also clicks the parent due to default event bubbling. To get the effect you want, stop the bubble via .stopPropagation(), like this:

$('.list-item .close').live('click', function(e) {
    $(this).parent().removeClass('list-item-active');
    e.stopPropagation();
});

You can test it out here.


Try this one:

$(document).ready(function(){
    $('.list-item').live('click', function() {
        if (!$(this).hasClass('list-item-active'))
            $(this).addClass('list-item-active');
    });
    $('.list-item .close').live('click', function() {
        $(this).parent().removeClass('list-item-active');
        return false;
    });
});

Note the new return false: otherwise the event will be caught by the $('.list-item').live instead of the one you want, the $('.list-item .close').live.


Because you didn't return false in the second event handler. Without a return false; the event will be handled be parent too which reads the class after you have removed it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜