开发者

jQuery next() not working with live()

开发者 https://www.devze.com 2023-02-05 08:16 出处:网络
When I try and use the jQuery next() method it doesn\'t work with live(). First off, here is my code: $(\".toggle_button\").live(\'click\', function() {

When I try and use the jQuery next() method it doesn't work with live().

First off, here is my code:

$(".toggle_button").live('click', function() {
    $(this).html($(this).html() == '-' ? '+' : '-');
    $(this).next(".info_section").toggle(400);
});

Here's the HTML

<div class='section_toggle_container'>
    <div class='toggle_button'>-</div>
    <strong>Driver Information:</strong>
</div>
<div class='info_section'>
    info here
</div>

Would the problem maybe lie in the fact that .toggle_button is nested, making .info_section unreachable?

The second line works great, because it's modifying the element given the live() event. The third line, however, is where the problem's at. This is because it's using next().

Can anyone help me with a solution for my next() 开发者_Go百科problem?


Looking at the HTML should't your statement:

$(this).next(".info_section").toggle(400);

be:

$(this).parent().next(".info_section").toggle(400);


While you have the working answer, I wanted to leave a suggestion about your toggling of the - and +, I'd suggest using text() instead of HTML, and using the inherent text (for text(), html for html()):

$(".toggle_button").live('click', function() {
    $(this).text(function(index,text) {
        return text == '-' ? '+' : '-';
    });
    $(this).parent().next(".info_section").toggle(400);
});

And, further, I'd suggest caching your $(this), if you're calling it more than once it's worthwhile using caching to prevent having to recreate it subsequently, leading to:

$(".toggle_button").live('click', function() {
    var $this = $(this);
    $this.text(function(index,text) {
        return text == '-' ? '+' : '-';
    });
    $this.parent().next(".info_section").toggle(400);
});

Of course, if you're using a version of jQuery greater than, or including, 1.7, then you should be using the on() method, rather than the (since jQuery 1.7) deprecated live(), which would give:

$(".toggle_button").on('click', function() {
    var $this = $(this);
    $this.text(function(index,text) {
        return text == '-' ? '+' : '-';
    });
    $this.parent().next(".info_section").toggle(400);
});

This really is just advice, though, unfortunately posted as an answer to prevent incomprehensible code being pasted into a comment.

References:

  • html().
  • live().
  • on().
  • text().
0

精彩评论

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