jquery - 单击时添加 div,然后在每次单击时切换它

标签 jquery append toggle

  1. 我尝试点击添加,添加的内容将第一次出现。

  2. 添加后,我想点击添加,它只会切换“已添加”,而不是每次点击都添加“已添加”

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/

相关文章:

javascript - 更改 Google map 的 RichMarker 光标

list - 如何在不在erlang中创建新变量的情况下将元素添加到现有列表?

javascript - 按下折叠或展开图片时如何连接我的滑动切换按钮

jQuery 在函数之间切换 - 执行零、一、二、三...次

javascript - 如何使用 JavaScript 显示/隐藏隐藏的 HTML 表格行(无 jQuery)

jquery - 一个奇怪的 contains (*) jQuery 选择器

具有淡入淡出效果的 JQuery jCarouselLite 插件

java - append 到文件

python - 类中的列表未转储到文件

javascript - 如果未勾选复选框,则禁用提交按钮