简体   繁体   English

jQuery-使元素连续追加而不是替换

[英]Jquery - Make element append continously instead of replace it

I wanna make some 'invitation list'. 我想做一些“邀请清单”。 When we type other people email and click the add button , email we type is show on the bottom. 当我们键入其他人的电子邮件并单击添加按钮时 ,我们键入的电子邮件将显示在底部。 The code from me is looks like below: 来自我的代码如下所示:

HTML 的HTML

<input type="email" name="invite_people" placeholder="Invite someone">
<a href="#!" class="add_people">Add</a>

<div class="people_invited">
   <!--
      this element
    <div>
       <span class="people_added"></span>
    </div>
      is added by Jquery
   -->
</div>

Jquery jQuery的

$(".add_people").click(function () {
            var orang_yg_diinvite = $("input[name='invite_people']").val();
            $(".people_invited").append("<div><span class='people_added'></span></div>");
            $("span.people_added").text(orang_yg_diinvite);
        });

It just worked. 它只是工作。 But it worked only for the first time when we add people. 但是,这仅在我们增加人员时才起作用。 When we add people again, the first 'add list people' is replace by the last we add. 当我们再次添加人员时,第一个“添加列表人员”将替换为最后添加的人员。 What I want is each <span class="people_added"> is have different text inside of it. 我想要的是每个<span class="people_added">里面都有不同的文本。 Something like bitbucket 像位桶之类的东西

在此处输入图片说明

not like that (My result) 不喜欢(我的结果)

在此处输入图片说明

Please help me :) 请帮我 :)

The problem of your code is this line: 您的代码的问题是这一行:

$("span.people_added").text(orang_yg_diinvite);

This selector is unique only the first time. 该选择器仅在第一次时是唯一的。 Later you have more spans with people_added class - so you are assigning new text to all of these spans. 稍后,您可以使用people_added类获得更多跨度-因此您将为所有这些跨度分配新的文本。

You can append the text for the new element while you are creating it, like: 您可以在创建新元素时为其添加文本,例如:

var divInnerText = "myText";
var newDiv = $("<div>" + divInnerText + "</div>");

It will produce the following element: <div>myText</div> 它将产生以下元素: <div>myText</div>

You can solve your problem using this approach: 您可以使用以下方法解决您的问题:

$(".add_people").click(function () {
    var orang_yg_diinvite = $("input[name='invite_people']").val();
    $(".people_invited").append("<div><span class='people_added'>" + orang_yg_diinvite + "</span></div>");
});

The problem was this line 问题是这条线

$("span.people_added").text(orang_yg_diinvite);

What it does is it overwrites the whole span elements with new value instead what you do is add it to the append function like this 它的作用是用新值覆盖整个span元素,而不是像这样将其添加到append函数中

$(".add_people").click(function () {
        var orang_yg_diinvite = $("input[name='invite_people']").val();
        $(".people_invited").append("<div><span class='people_added'>"+orang_yg_diinvite+ "</span></div>");

    });

link here on jsfiddle 链接到jsfiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM