I have some code at here:
<body>
<p>This is a paragraph.</p>
<button>click me</button>
</body>
$(document).ready(function(){
$("button").click(function(){
$("p").hide().after('<p>hello world</p>');
});
});
Actually, I've using JQuery 2.0.2
also.
"<p>This is paragraph<p>"
will be replaced by <p>hello world</p>
.
The first click is successful. However, many hello world
with the growth rate of progression show after the first hello world
shown. For example:
<p style="display: none;">This is a paragraph.</p>
<p>hello world</p>
<p style="display: none;">hello world</p>
<p>hello world</p>
<button>click me</button>
Why the first <p>hello world</p>
wasn't be replaced by the new one?
Doesn't it suppose to show one p tag only?
That's cause you're creating paragraphs
<p>hello world</p>
and on every click the $('p')
is a collection of all p
elements on your page.
The more paragraphs you have... more appends. live demo - issue example
An element, even if set to display:none
using .hide()
, is still present in your document..
$("button").click(function(){
$("p").html('hello world');
});
$("button").click(function(){
$("p").text('hello world');
});
$("button").click(function(){
$("p").replaceWith('<p>hello world</p>');
});
$("button").click(function(){
$("p").after('<p>Hello world</p>').remove();
});
If only you want to change the text you an do like this
$(document).ready(function(){
$("button").click(function(){
$("p").html('hello world');
});
});
JS FIDDLE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With