简体   繁体   中英

Jquery will not select button after class has been toggled

I have some jquery that will, when a button is clicked, switch a class from a button to a different class (ie on click switch class from #testButton from .first to .second with an image toggle to show it works). The first click works well and it toggles the image, but the second click does not do anything. It seems as if it is not recognizing the new class. Here is a fiddle.

https://jsfiddle.net/myfb44yu/

This is the problematic javascript.

$(document).ready(function(){
  $('.first').click(function(){
    alert('works');
    $('#testButton').toggleClass('first', 'second');
  });

  $('.second').click(function(){
    alert("works");
    $('#testButton').toggleClass('second', 'first');
  });
});

The interesting thing is that it works when I use an alert() to check but not when I try to change an img src.

Your main issue here is a syntax error in regards to your .toggleClass , but seeing as others have addressed that, I'd like to point out that you should consider re-thinking how you apply your listeners - just as good habit moving forward.


An overview of jQuery Event Bindings

Think of the elements on your page as items in a store. You're an employee, and your manager says "Go put a red tag on anything in the toys department", and so you do. The next day, he puts 10 new toys in the toy department, and says to you "Why don't all the toys have red tags on them?" He then moves one of the toys to the clothing section and asks you, "Why does this item have a red tag on it?" It's simple. You put the red tags on anything in the toys department when he told you to do it - things got moved around afterwards.

The toys in this example would be your .first and .second elements.

This is how jQuery event bindings work - they only apply to elements that satisfied the selector at the time the event was initialized.

So, if you do $('.myClass').click(); , then put .myClass on five buttons - none of those buttons will call this function, as they didn't have listeners put on them.

Similarly, if you put a listener on an element using class, but then remove the class from that element, it will maintain the bound event .


The Solution

$(document).on("click", ".first", function() { } );

This is known as event delegation .

In continuing with my analogy from before, this would be the equivalent of skipping tagging the items altogether, and instead just deciding whether or not they're a toy when the customer brings them to the cash register.

Instead of putting the listener on specific elements, we've put it on the entire page. By using ".first" as the second parameter (which takes a selector), the function will only be executed if the element has class first .

Hope this helps.

EDIT : As I was typing, JHecht left a good answer that points out the same issue I outlined above.

N number of elements can have the same class name ,so that's the reason if your trying to search it as $('.classname') returns an array ,so that's the reason your code is not working. class selector

Id is unique,each element should have a single id . In your code button has two id's and for the same button your trying to toggle first and second,you need not have two separate events for first and second

instead you can write as following

check this snippet

 $(document).ready(function() { var firstElements = $('.first') var first = firstElements[0]; var secondElements = $('.second'); var second = secondElements[0] $("#testButton").click(function() { alert('works'); $(this).toggleClass('first').toggleClass('second'); }); }); 
 .first { color: red; } .second { color: green; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <img src="img/images.jpeg" alt="" id="testImage"> <div id="testDiv"> <button type="button" id='testButton' class='first'>Hi</button> </div> 

Hope it helps

Ho about this solution. Hope it helps!

 $(document).ready(function(){ $("#testButton").click(function(){ if($(this).prop("class") === "first"){ alert('first'); $(this).removeClass("first").addClass("second"); } else if($(this).prop("class") === "second"){ alert("second"); $(this).removeClass("second").addClass("first"); } }); }); 
 .first{ color: red; } .second{ color: blue; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <img src="img/images.jpeg" alt="" id="testImage"> <div id="testDiv"> <button type="button" id='testButton' class='first'>Hi</button> </div> 

I hope that what I am about to say makes more sense than I feel it does.

Your issue is that when you assign the click events, there is not currently an element that has a class of .second .

Also, your code is wrong. toggleClass accepts a few arguments, the first is a string of classes, the second is an optional parameter to check whether or not to toggle the classes on or off.

A way to accomplish what you want without changing a whole lot of code is event delegation, shown below.

 $(function() { $(document).on('click', '.btn-first,.btn-second', function() { //here we are adding the click event on the document object, and telling it that we only want to delegate this event to an object that matches the classes of .btn-first or .btn-second. //Note: to those saying "why not just do it on the .btn class an avoid having to do this", it is so he can see what delegation looks like. But you are correct, with this markup it would be better to simply add the click event on the .btn class. $(this).toggleClass('btn-first btn-second'); }); }); 
 .btn { padding: 4px 8px; border-radius: 3px; border: 1px solid grey; } .btn-first { background-color: green; border-color: green; } .btn-second { background-color: orange; border-color: orange } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <img src="img/images.jpeg" alt="" id="testImage"> <div id="testDiv"> <button type="button" id='testButton' class='btn btn-first'>Hi</button> </div> 

A combination of javascript, CSS and HTML to toggle the class of #testButton when any element of class "first" or "second" is clicked, including the test button itself. The posted code was changed to supply JQuery's .toggleClass method with a space separated list of class names. Click "run snippet" to test the effect.

 $(document).ready(function(){ $('.first').click(function(){ $('#testButton').toggleClass('first second'); }); $('.second').click(function(){ $('#testButton').toggleClass('first second'); }); }); 
 .first { border: thick outset green;} .second { border: thick inset red;} 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p class="first">This paragraph has first class</p> <p class="second">This paragraph has second class</p> <button type="button" id="testButton" class="first">this button starts out first class</div> 

The script can then be simplified by combining multiple class names in a single selector, leaving just:

$(document).ready(function(){
    $('.first, .second').click(function(){
       $('#testButton').toggleClass('first second');
    });
});
  • Make a neutral class that the buttons both share ( .btn ).
  • Then add one of the state classes to each button ( .first or .second ).
  • Delegate the click event to the neutral class only ( $('.btn').on('click',... ).
  • Then toggle both state classes on this ( $(this).toggleClass('first second'); )
  • The images change by CSS, each button has 2 images which alternate between display:none/block according to the button's state class.
  • There is an example with the images outside of buttons and another example that doesn't toggle classes around.

SNIPPET

 $('.btn').on('click', function() { $(this).toggleClass('first second'); }); /* OR */ $('.alt').on('click', function() { $('.img').toggle(); }); 
 .first > .one { display: block; } .first > .two { display: none; } .second > .one { display: none; } .second > .two { display: block; } .first + .one { display: block; } .first + .one + .two { display: none; } .second + .one { display: none; } .second + .one + .two { display: block; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p>Use jQuery with CSS</p> <button class='btn first'> <img src='http://placehold.it/50x50/000/fff?text=1' class='one'> <img src='http://placehold.it/50x50/fff/000?text=2' class='two'> </button> <button class='btn second'> <img src='http://placehold.it/50x50/0e0/960?text=1' class='one'> <img src='http://placehold.it/50x50/fff/000?text=2' class='two'> </button> <br/> <br/> <button class='btn first'>Toggle</button> <img src='http://placehold.it/50x50/fc0/00f?text=1' class='one'> <img src='http://placehold.it/50x50/00f/fc0?text=2' class='two'> <button class='btn second'>Toggle</button> <img src='http://placehold.it/50x50/fc0/00f?text=1' class='one'> <img src='http://placehold.it/50x50/00f/fc0?text=2' class='two'> <p>Or use only jQuery no CSS</p> <img src='http://placehold.it/50x50/0e0/930?text=1' class='img'> <img src='http://placehold.it/50x50/930/0e0?text=2' class='img' style='display:none'> <button class='alt' style='display:block;'>Toggle</button> 

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