Add div on click, then toggle it on every click af

2020-07-17 07:32发布

  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/

8条回答
Rolldiameter
2楼-- · 2020-07-17 08:12

You can simplify a lot by creating and hiding the "added" div right in the beginning.

CSS:

#spin {display: none;}

HTML:

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

jQuery:

$(function(){
    $(".add").click(function(){
        $("#spin").toggle();
    });
});

In other words, rather than dynamically creating "Added" and then toggling visibility, just toggle visibility (starting in an invisible state).

查看更多
唯我独甜
3楼-- · 2020-07-17 08:14

Jquery:

$(function(){
    var NewContent='<div class="added">Added</div>';
    var handleAddItem = function($add) {
        var added = false,
            $spin = $('#spin'), //Suggest using something more relevant to the object getting clicked??
            $content = $(NewContent);
        $add.click(function(){
            if(added){
                added=true;
                $spin.after($content);
            }else{
                $content.toggle();
            }
        }
    };
    $(".add").each(function(){handleAddItem($(this));});
});
查看更多
登录 后发表回答