开发者

jQuery .live() with a parent link

I have some markup that looks like this:

<a href="#" class="someButton">
   <span class="play">play</span>
</a>

When I click play, the markup changes to this:

<a href="#" class="someButton">
   <span class="stop">stop</span>
</a>

I am binding to the parent link, which is always there, just the class of the child element changes. How do I do this with .live()?

This is my current code

$('.play').parent('a').live('click', function() {
    console.log('PLAY');
});

// stop
$('.stop').parent('a').live('click', function() {
    开发者_如何学编程console.log('stop');
});

I should also note that I dont have control over the markup changing as its a 3rd party video player but someone higher up in the organization.


$('.someButton').live('click', function(){
    if ( $(this).find('.stop').length ) {
        console.log('stop');
    } else if ( $(this).find('.play').length ) {
        console.log('play');
    }
});


You can only use ".live()" when your jQuery object was directly created by a selector. You can't "navigate" to somewhere else via things like "find()".

With the ".delegate()" API, it's more explicit (and thus probably more clear):

$('whatever').delegate(selector, events, handler);

The "selector" argument can only be a string. (Seems like it'd be nice if it could be a function.)


CSS

.play { color: green; }
.stop { color: red; }

Markup

<a href="#" class="someButton">
    <span class="play">Click</span>
</a>

Updated JS (thanks @patrick dw)

$('a:has(.play)').live('click', function() {
    $(this).find('span').removeClass('play').addClass('stop');
    alert('PLAY');
});

// stop
$('a:has(.stop)').live('click', function() {
    $(this).find('span').removeClass('stop').addClass('play');
    alert('stop');
});

jsfiddle here.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜