开发者

JQuery function does not work after changing ID

I have a simple file that has a Jquery script it in that loo开发者_运维百科ks like this:

<script type="text\javascript">     
$('.grey_title').click(function(){
        $(this).parent().find('.inner_div').slideToggle('slow');
    });
    $('#hideall').click(function(){
        $('.inner_div').slideUp('slow');
        $(this).parent().html("<span id=\"showall\">Show all Menus</span>");
    });
    $('#showall').click(function(){
        $('.inner_div').slideDown('slow');
        $(this).parent().html("<span id=\"hideall\">Hide all Menus</span>");
    });
   });
</script>
  <div><span id="hideall">Hide all Menus</span></div>

The function works fine while hiding menus and when you change the ID to showall in the HTML and the script to slideToggle, however when you click Hide all it will close all and according to Firefox, changes the item to be

<span id="showall">...</span>

but, when clicked again it does nothing. What could I be doing wrong?

the page


I expect the binding to fail since there is no showall when the binding is done

A better choice is to toggle

You may want to switch the functions around to match what is shown when the page loads

DEMO HERE

$('#hideall').toggle(
  function(){
    $('.inner_div').slideUp('slow');
    $(this).text("Show all Menus");
  },
  function(){
    $('.inner_div').slideDown('slow');
    $(this).text("Hide all Menus");
  }
);


When the id is gone, it detaches the event bound to it. You can try the live event binding.

$('#hideall').live('click', function(){
    $('.inner_div').slideUp('slow');
    $(this).parent().html("<span id=\"showall\">Show all Menus</span>");
});
$('#showall').live('click', function(){
    $('.inner_div').slideDown('slow');
    $(this).parent().html("<span id=\"hideall\">Hide all Menus</span>");
});


You need to use delegate or live to define the events. What the events above do is only bind the handler to the existing elements on the page while the live/delegate function bind to existing and future elements.

$(document).delegate('.grey_title', "click",function(){
        $(this).parent().find('.inner_div').slideToggle('slow');
 }).delegate('#hideall'."click", function(){
        $('.inner_div').slideUp('slow');
        $(this).parent().html("<span id=\"showall\">Show all Menus</span>");
}).delegate('#showall',"click", function(){
        $('.inner_div').slideDown('slow');
        $(this).parent().html("<span id=\"hideall\">Hide all Menus</span>");
});

</script>
  <div><span id="hideall">Hide all Menus</span></div>


You are binding to the click event to an element that does not yet exist... try this:

$('#showall').live('click', function(){
        $('.inner_div').slideDown('slow');
        $(this).parent().html("<span id=\"hideall\">Hide all Menus</span>");
    });
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜