javascript - 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 属性,我不想要它们。
解决方案
因此,首先检查是否选中了旧复选框。您可以通过以下几种方式执行此操作:
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>
推荐阅读
- python - 动态优化需要帮助:错误消息:通过的 f0 在优化算法中具有多于 1 个维度
- java - Spring Security 加密密码问题
- c# - 如何将此 SQL 转换为 LINQ?
- python - 转置和重塑究竟是如何工作的?
- opencv - 使用 ML 中的特征提取方法将灰度图像转换为彩色图像
- react-native - 在 Mac OS Catalina 上安装 Watchman 无法使用 Home brew
- wpf - 为什么我点击按钮后左眼不再眨眼
- c# - C# WPF TextBox 对文本更改的调用方法
- python - 使用pandas groupby并申请累积积分
- r - Tidyquant 中权重随时间和资产变化的投资组合