单击时添加 div,然后在每次单击时切换它 [英] Add div on click, then toggle it on every click after that

查看:32
本文介绍了单击时添加 div,然后在每次单击时切换它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  1. I'm trying to click add and the content of add will appear for the first time.

添加后,我想点击添加,它只会切换添加",而不是在每次点击时添加添加"

After it's added, I want to click add and it will only toggle "added", instead of adding "added" on each click

查询:

$(function(){
    var NewContent='<div class="added">Added</div>'
    $(".add").click(function(){
        $("#spin").after(NewContent);
    });
});

HTML:

<span class="add">add</span>
<span id="spin"></span>

这是一个小提琴: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/

这篇关于单击时添加 div,然后在每次单击时切换它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆