Changing html content back and forth with jQuery

泄露秘密 提交于 2019-12-13 16:16:12

问题


I want to use jQuery to dynamically change an html element every time it's clicked, back and forth (from A to B to A to B etc...)

Right now I use an empty <div> that is filled with jQuery:

$('#cf_onclick').append('<h2>A</h2>'); 

And then changed:

$(document).ready(function() {
$("#cf_onclick").click(function() {
$("#cf_onclick").html("<h2>B</h2>");
});
});

But I cannot figure out how to move it back to <h2>A</h2>. I am guessing that .empty() jQuery function might work...


回答1:


One way is to use the .toggle() method, and trigger it for the first time as well

$(document).ready( function(){
    $("#cf_onclick").toggle(
        function(){$(this).html("<h2>A</h2>");},
        function(){$(this).html("<h2>B</h2>");}
    ).click();
});

demo http://jsfiddle.net/gaby/ufXxb/


Alternatively you could create two h2 tags and just alternate between them.

$(document).ready( function(){
    $('#cf_onclick').append('<h2>A</h2><h2 style="display:none">B</h2>');
    $("#cf_onclick").click(function(){
        $('h2', this).toggle();
    });
});

demo http://jsfiddle.net/gaby/ufXxb/1/




回答2:


Try using the toggle() function: http://api.jquery.com/toggle/ It's a way of alternating an action with each click.




回答3:


You could do this:

$(document).ready(function() {
  $("#cf_onclick").click(function() {
    var currentOpt =  $("#cf_onclick h2").html();
    currentOpt = (currentOpt == 'B' ? 'A' : 'B');
    $("#cf_onclick").html("<h2>"+currentOpt+"</h2>");
  });
});

Hope this helps



来源:https://stackoverflow.com/questions/5924672/changing-html-content-back-and-forth-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!