$(document).ready(function() { $(".A1").click(function() { $(".P1").toggle("slow"); $(".A1").html(($(".A1").html() === "+" ? $(".A1").html("-") : $(".A1").html("+"))); }); });
A little explanation: I install $("#A1").html()
with the product of the tertiary operator, using it to check the current value of the text #A1
. If it is a +
, I set the text of the element to -
otherwise I set it to +
.
However, you said effective. For this, it is important to note that if you intend to use the selector twice or more in the same function, you must save the jQuery object, which is obtained from the selector that you specified in the variable, so you do not need to re-run the selector every time. Here is the code with this modification:
$(document).ready(function() { $(".A1").click(function() { var $A1 = $(".A1"); $(".P1").toggle("slow"); $A1.html(($A1.html() === "+" ? $A1.html("-") : $A1.html("+"))); }); });
source share