Changing html content back and forth with jQuery

2019-07-16 12:29发布

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...

3条回答
再贱就再见
2楼-- · 2019-07-16 13:05

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/

查看更多
Deceive 欺骗
3楼-- · 2019-07-16 13:05

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

查看更多
手持菜刀,她持情操
4楼-- · 2019-07-16 13:13

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

查看更多
登录 后发表回答