首页 > 解决方案 > JQuery:识别重复元素并删除旧条目

问题描述

我最初有以下复选框:

<div class="controls">
  <label class="checkbox" name="Flow">Flow
    <input type="checkbox" value="Flow" name="1" id="8" checked="checked">
  </label>
 <label class="checkbox" name="Timer">Timer
   <input type="checkbox" value="Timer" name="1" id="17" checked="checked">
 </label>
</div>

形成我的数据源,我正在附加动态复选框:

data = [{
  "id": 3,
  "name": "Respiratory & COPD",
  "slug": "respiratory_and_copd",
  "tests": [{
      "id": 4,
      "name": "Oxygen"
    },
    {
      "id": 6,
      "name": "Pressure"
    },
    {
      "id": 8,
      "name": "Flow"
    },
    {
      "id": 17,
      "name": "Timer"
    }
  ]
}]


$.each(data[0].tests, function(key, val) {
  $('.controls').append('<label class="checkbox" name="' + val.name + '">' +
      '<input type="checkbox" value="' + val.name + '" id="' + val.id + '">' + val.name + '</label>');
});

您可以看到Flow&Timer也正在再次创建。

如何删除旧的flow&Timer并选中新的Flow&Timer复选框?

旧的Flow&Timer有 name 属性,我不想要它们。

JSFIDDLE

标签: javascriptjquery

解决方案


因此,首先检查是否选中了旧复选框。您可以通过以下几种方式执行此操作:

elem.checked    true (Boolean) Will change with checkbox state
$( elem ).prop( "checked" )     true (Boolean) Will change with checkbox state
elem.getAttribute( "checked" )  "checked" (String) Initial state of the checkbox; does not change
$( elem ).attr( "checked" ) (1.6)   "checked" (String) Initial state of the checkbox; does not change
$( elem ).attr( "checked" ) (1.6.1+)    "checked" (String) Will change with checkbox state
$( elem ).attr( "checked" ) (pre-1.6)   true (Boolean) Changed with checkbox state

(来自http://api.jquery.com/prop/

我喜欢返回字符串的那个,所以我可以很容易地将它插入到 html 中。在此之后,您可以删除旧复选框并创建一个新复选框。

顺便说一句:您的脚本使项目具有重复的 id(标签和复选框具有相同的 id)。这会给你带来麻烦。改变它会更安全。

data = [{
  "id": 3,
  "name": "Respiratory & COPD",
  "slug": "respiratory_and_copd",
  "tests": [{
      "id": 4,
      "name": "Oxygen"
    },
    {
      "id": 6,
      "name": "Pressure"
    },
    {
      "id": 8,
      "name": "Flow"
    },
    {
      "id": 17,
      "name": "Timer"
    }
  ]
}]


$.each(data[0].tests, function(key, val) {

ischecked=$('#'+val.id).attr( "checked" )
$('#'+val.id).parent().remove()

  $('.controls').append('<label class="checkbox" for="' + val.id + '" name="' + val.name + '">' +
      '<input type="checkbox" value="' + val.name + '" id="' + val.id + '" '+ischecked+'>' + val.name + '</label>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/twitter-bootstrap/2.2.2/css/bootstrap-combined.min.css" crossorigin="anonymous">

<div class="controls">
  <label class="checkbox" name="Flow">Flow
    <input type="checkbox" value="Flow" name="1" id="8" checked="checked">
  </label>
  <label class="checkbox" name="Timer">Timer
    <input type="checkbox" value="Timer" name="1" id="17" checked="checked">
  </label>
</div>


推荐阅读