简体   繁体   English

使用 jquery 从数组列表中添加和删除数组项

[英]Add and remove array items from array list using jquery

I would like to establish a function where you can add and remove users我想建立一个可以添加和删除用户的功能

  1. to comma separated string which is stored in an input field and到存储在输入字段中的逗号分隔字符串和

  2. Show the list of added users in html to delete each line item if needed.如果需要,在 html 中显示添加的用户列表以删除每个行项目。

Unfortunately I have the following issues in my code:不幸的是,我的代码中有以下问题:

  1. The comma separated userlist + html list adds the user to each new created line item逗号分隔的 userlist + html list 将用户添加到每个新创建的行项目

  2. Deleting one line item from HTML list doesn't work as expected.从 HTML 列表中删除一个行项目没有按预期工作。

在此处输入图片说明

Expected result:预期结果:

input value: Adam,Bertha,Caesar输入值: Adam,Bertha,Caesar

html value: html 值:

Adam (delete)亚当(删除)

Bertha (delete)伯莎(删除)

Caesar (delete)凯撒(删除)

Could you please have a look at my js fiddle and give me a hint how to display the userlist correctly in html + input field?你能看看我的js fiddle并给我一个提示如何在 html + 输入字段中正确显示用户列表吗?

 var users = []; $("#adddis").click(function() { var values = $('input[type=text]').map(function() { return $(this).val(); }).get().join(); $('#adddisnames').val(""); addUser(values); }); function buildUserlist() { var html = "<hr>"; for (var i = 0; i < users.length; i++) { html += users[i] + ' <a href="#" onclick="removeUser(' + i + '); return false;">X</a><br>'; }; $('#userdiv').html(html); } function addUser(values) { users.push(values); buildUserlist(); $('#storadddis').val(users); } function removeUser(index) { users.splice(index, 1); buildUserlist(); $('#storadddis').val(users); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <label>Name</label> <input type="text" id="adddisnames" value=""> <input type="button" name="get_value" id="adddis" value="add"> => <input type="text" id="storadddis" size="35"> <div id="userdiv"></div>

First : Change this code to this第一:将此代码更改为此

 $("#adddis").click(function() {
     if ($('#adddisnames').val().length !== 0) {
       addItem($('#adddisnames').val());
     } else {
        alert ('Please add User!')
     }
});

Next : change this code also to this下一个:将此代码也更改为此

function addItem(values) {
  users.push(values);
  buildUserlist();
  $('#storadddis').val(users.toString());
  $('#adddisnames').val("");

}  

You should use the users array as the master of the data.您应该使用users数组作为数据的主人。 When adding names, don't take that input value together with what is in the rightmost input .添加名称时,不要将该input值与最右边的input值一起使用。 Consider the text in that rightmost control as an output , not as input.将最右边控件中的文本视为输出,而不是输入。

As you use jQuery, I would also use jQuery to the full for populating the div element.当您使用 jQuery 时,我也会完全使用 jQuery 来填充div元素。 This way you are also sure that any characters in the usernames, that could be misinterpreted as HTML, are properly escaped.通过这种方式,您还可以确保用户名中的任何可能被误解为 HTML 的字符都已正确转义。

For the click handler: it is probably better to use event delegation, and only define one click handler on the div element, once .对于点击处理程序:最好使用事件委托,并且只在div元素上定义一个点击处理程序,一次 You can know which link was clicked with the .index() jQuery method.您可以知道使用.index() jQuery 方法单击了哪个链接。

 var users = []; $("#adddis").click(function() { addUser($('#adddisnames').val().split(",")); // pass an array as argument $('#adddisnames').val(""); }); $('#userdiv').on("click", "a", function () { // event delegation removeUser($(this).parent().index()); }); function buildUserlist() { // Use jQuery functions to build the DOM list: $('#userdiv').empty().append( users.map(function (user) { return $("<div>").text(user).append($("<a>").attr("href", "#").text("✘")); }) ); $('#storadddis').val(users); // do this here -- as it is part of the output } function addUser(values) { // Expect an array as argument here values = values.map(value => value.trim()) // trim values .filter(Boolean); // ... and exclude empty entries users = users.concat(values); // join the two arrays users = Array.from(new Set(users)); // make list unique buildUserlist(); } function removeUser(index) { users.splice(index, 1); buildUserlist(); }
 a[href] { color:red; padding-left: 5px; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <label>Name</label> <input type="text" id="adddisnames" value=""> <input type="button" name="get_value" id="adddis" value="add"> => <input type="text" id="storadddis" size="35"> <div id="userdiv"></div>

without Telling you to update everything to make it cleaner.无需告诉您更新所有内容以使其更干净。 I think your simple fix is to update this line:我认为您的简单解决方法是更新这一行:

var values = $('input[type=text]').map(function() {

To

var values = $('input[id=adddisnames]').map(function() {

The way you had it before is it was finding both input fields, and then duplicating your results您以前的方式是查找两个输入字段,然后复制您的结果

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

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