我尝试点击添加,添加的内容将第一次出现。
添加后,我想点击添加,它只会切换“已添加”,而不是每次点击都添加“已添加”
Jquery:
$(function(){
var NewContent='<div class="added">Added</div>'
$(".add").click(function(){
$("#spin").after(NewContent);
});
});
HTML:
<span class="add">add</span>
<span id="spin"></span>
这是一个 fiddle :http://jsfiddle.net/Abgec/
最佳答案
$(function(){
//start with `NewContent` being the HTML to add to the page
var NewContent='<div class="added">Added</div>'
$(".add").click(function(){
//check if `NewContent` is empty or not
if (NewContent != '') {
//if `NewContent` is not empty then add it to the DOM
$("#spin").after(NewContent);
//now that `NewContent` has been added to the DOM, reset it's value to an empty string so this doesn't happen again
NewContent = '';
} else {
//this is not the first click, so just toggle the appearance of the element that has already been added to the DOM
//since we injected the element just after the `#spin` element we can select it relatively to that element by using `.next()`
$('#spin').next().toggle();
}
});
});
这是一个演示:http://jsfiddle.net/7yU3n/
.toggle()
的文档:http://api.jquery.com/toggle/
关于jquery - 单击时添加 div,然后在每次单击时切换它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9384957/