使用jQuery来回更改HTML内容 [英] Changing html content back and forth with jQuery
问题描述
我想用jQuery来动态地改变一个HTML元素,每次点击它时,来回地(从A到B到A到B等等......)
现在我用一个空的< div>
来填充jQuery:
$( '#cf_onclick')附加。( '< H2>一种与LT; / H2>');
然后更改:
($#$)$($#$) < h2> B< / h2>);
});
});
但我不知道如何将它移回< h2> A< / H2>
。我在猜测 .empty()
jQuery函数可能会工作...
一种方法是使用 .toggle()
method ,并首次触发它。
$(document).ready(function( ){
$(#cf_onclick)。toggle(
function(){$(this).html(< h2> A< / h2>);},
函数(){$(this).html(< h2> B< / h2>);}
).click();
});
演示 http://jsfiddle.net/gaby/ufXxb/
或者,您可以创建两个 h2
标签,然后在它们之间切换。
$('#cf_onclick')。append('< h2> A< / h2>< h2 style =display:none>点击(函数(){
$('h2',this).toggle();
});
$(#cf_onclick)。
});
演示 http://jsfiddle.net/gaby/ufXxb/1/
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...
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/
这篇关于使用jQuery来回更改HTML内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!