求助:点击按钮无法切换Glyphicon类,需实现glyphicon-plus与-minus切换
Hey there, let's get that glyphicon toggle working properly! The main issue in your code is how you're trying to select the <span> element inside the button—here's what's going wrong and how to fix it:
What's Breaking It
Your line $(this + " span") is invalid syntax. this in that context refers to the actual DOM button element, not a string selector, so you can't just concatenate it with " span" to find the child element. That's why the glyphicon classes aren't updating when you click the button.
Corrected Code
Replace that faulty selector with jQuery's .find() method (which looks for descendant elements) to target the glyphicon span inside the clicked button. Here's the fixed version:
$("#button-list button").each(function(index) { $(this).on("click", function() { // Toggle button styles $(this).toggleClass("btn-default btn-success"); // Toggle glyphicon classes correctly $(this).find("span").toggleClass("glyphicon-plus glyphicon-minus"); }); });
Bonus: Direct Child Alternative
If the <span> is a direct child of the button (no nested elements in between), you can also use .children("span") instead of .find("span")—it's slightly more efficient for direct parent-child relationships.
Quick Additional Checks
- Double-check your jQuery script URL: yours is truncated (
https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1....). Make sure it's a complete, valid URL (likehttps://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js) so jQuery loads without issues. - Confirm every button in
#button-listhas a<span>child with eitherglyphicon-plusorglyphicon-minusas its initial class—without that, there's nothing to toggle!
内容的提问来源于stack exchange,提问作者user9402741

