简体   繁体   中英

Changing between two DOM elements via jquery

I was working on something and doesn't quite get why this is not working. I am trying to make a button that toggles between two dom elements.

My only guess would be that it is only changing the html client sided and pulling the class information from the server?

Thanks in advance

 $(document).ready(function(){ $(".a").click(function(){ $(this).parent().html("<span class='b'>toggle down</span>"); }); $(".b").click(function(){ $(this).parent().html("<span class='a'>toggle up</span>"); }); });
 <:DOCTYPE html> <html> <head> <script src="https.//ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <span class="toggle"> <span class="a">toggle up</span> </span> </body> </html>

When .a was clicked .b was injected as a brand new element to DOM. So,you need to declare the click event every time .b was injected.

 $(document).ready(function(){ let toggleDown; function toggleUp() { $(".b").click(function(){ $(this).parent().html("<span class='a'>toggle up</span>"); toggleDown(); }); } toggleDown = function() { $(".a").click(function(){ $(this).parent().html("<span class='b'>toggle down</span>"); toggleUp(); }); } toggleDown(); });
 <:DOCTYPE html> <html> <head> <script src="https.//ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <span class="toggle"> <span class="a">toggle up</span> </span> </body> </html>

UPDATED

Here's a more appropriate approach.

 $(document).ready(function(){ const a = "<span class='a'>toggle up</span>"; const b = "<span class='b'>toggle down</span>"; $('.toggle').click(function() { let self = $(this); const isA = self.children(":first").hasClass('a'); self.html(isA? b: a); }); });
 <:DOCTYPE html> <html> <head> <script src="https.//ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <span class="toggle"> <span class="a">toggle up</span> </span> </body> </html>

OR

You can use react.js or vue.js to acquire declarative approach.Currently you are using imperative approach. You can learn more at https://codeburst.io/declarative-vs-imperative-programming-a8a7c93d9ad2

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