加上点击分区,然后拨动它之后的每一次点击 [英] Add div on click, then toggle it on every click after that

查看:124
本文介绍了加上点击分区,然后拨动它之后的每一次点击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  1. 我试图单击Add并添加的内容将出现首次。


  2. 它添加

    后,我要点击添加,它只会切换补充,而不是加入补充说:每次点击


jQuery的:

  $(函数(){
    VAR NewContent ='< D​​IV CLASS =添加>&添加的LT; / DIV>'
    $(加)。点击(函数(){
        $(#旋转)后(NewContent)。
    });
});

HTML

 <跨度类=添加>添加< / SPAN>
&所述;跨度的id =自旋>&下; /跨度>

下面是一个小提琴: http://jsfiddle.net/Abgec/


解决方案

  $(函数(){    //使用`NewContent`开始作为HTML添加到页面
    VAR NewContent ='< D​​IV CLASS =添加>&添加的LT; / DIV>'
    $(加)。点击(函数(){        //检查是否`NewContent`为空或不
        如果(NewContent!=''){            //如果`NewContent`不为空,然后将其添加到DOM
            $(#旋转)后(NewContent)。            //现在`NewContent`已被添加到DOM,重置价值为空字符串所以这不会再发生
            NewContent ='';
        }其他{            //这是不是第一次点击,这样只需拨动一个已经被添加到DOM元素的外观
            //因为我们注入的元素只是`#spin`元素之后,我们可以用'。接下来比较中选择该元素()`
            $('#旋转')next()的切换()。
        }
    });
});

下面是一个演示: http://jsfiddle.net/7yU3n/

文件为 .toggle() HTTP://api.jquery。 COM /切换/

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

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

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>

Here's a 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();
        }
    });
});

Here is a demo: http://jsfiddle.net/7yU3n/

Docs for .toggle(): http://api.jquery.com/toggle/

这篇关于加上点击分区,然后拨动它之后的每一次点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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