简体   繁体   中英

Jquery button on click toggle text and css class of another element

I am making a jquery on click event that toggles a css class of div#foo (appending it after the existing class) but also needs to toggle the text of the button on click between show/hide.

<script>
$(document).ready(function(){
  $("button.toggler").click(function(){
    $("#foo").toggleClass("maximize");
    $("button.CsToggle").text(!text == "Expand" ? "Hide" : "Expand");
  });
});
</script>

<div id="foo" class="preExistingClass">
  <div>
    <button class="toggler">Expand</button>
  </div>
</div>

I have the class toggle working properly but not the text toggle. Where did I go wrong?

Use the html() function to set the innerHtml of the button. The selector should also be, $("button.toggler") . Also you need to have a variable text available, I'm assuming your business logic will determine how it is set..

$(document).ready(function(){
  $("button.toggler").click(function(){
    $("#foo").toggleClass("maximize");
    $(this).html($(this).html() == "Expand" ? "Hide" : "Expand");
  });
});

Working Example: http://jsfiddle.net/z5QVM/

$("button.CsToggle").toggle(function(){
 if ( $(this).text == "Expand"){ 
     // code
     }
  else {
     //code
   }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM