如何在jquery中删除重复的值

时间:2016-02-15 00:30:53

标签: javascript jquery

下面的代码会在框中附加文字,以避免输入重复值。?

 $('#plan td.n').click(function(){
 $(this).html('B').css("background-color","red");
 $("input:text").val(this.id);

 var toAdd = $("input[name=checkListItem]").val();  
 $(".list").append("<div class = 'item'>" + toAdd + "</div>")//add the seat number to box 



 });

3 个答案:

答案 0 :(得分:2)

我可能会在下面做这样的事情。希望它有所帮助

div

答案 1 :(得分:0)

假设您的标记看起来像这样:

<input name="checkListItem" value=""/>
<input type="submit" class="addItem" value="Add/Remove"/>
<div class="list">

</div>

您可以添加一个事件,该事件过滤与checkListItem输入的当前.val()的文本(确切)匹配的项目,如果它是重复项,则允许您删除列表中的项目。

$('.addItem').on('click', function() {

  var toAdd = $("input[name=checkListItem]").val(),
      exists = $('.item').filter(function() {
                 return $(this).text() == toAdd;
               });

  if (exists.length > 0) {
    exists.remove();
  } else {
    $(".list").append("<div class = 'item'>" + toAdd + "</div>");
  }

});

https://jsfiddle.net/milesrobinson/563h1fq6/

答案 2 :(得分:0)

// if you don't care the performance, this is the easy way
var finded = false;
$(".list > .item").each(function(idx){
    if (toAdd === $(this).html()) {
        finded = true;
        return false;
    }
});

if (!finded) {
     $(".list").append("<div class = 'item'>" + toAdd + "</div>")
}
相关问题