jQuery的 - 指数()函数返回错误的索引(复选框并选择)
问题描述:
我创建的复选框元素和选择与前面提到的名单相同的值列表。我实现要做的是如果我更改复选框选择,选择列表自动更新自己与相同的名称选项复选框。我在纯的JavaScript创造了这个(它的工作)是这样的:jQuery的 - 指数()函数返回错误的索引(复选框并选择)
function addChckBoxListener() {
for (var i = 0; i < chckBox.length; i++) {
(function(index) {
chckBox[i].addEventListener("change", function() {
update(0, index);
});
})(i);
}
}
function addSelectListListener() {
selectList.addEventListener("change", function() {
update(1, this.selectedIndex);
});
}
后来,我想实现与jQuery的库相同,但它的指数()函数返回错误的索引。我不知道为什么。下面是相同的代码,但在jQuery的:
function addChckBoxListener() {
chckBox.each(function() {
$(this).change(function() {
update(0, $(this).index());
});
});
}
function addSelectListListener() {
selectList.change(function() {
update(1, $(this).selectedIndex);
});
}
这里是我的HTML代码:
<body>
<div>
<ul>
<li><input type="checkbox" value="red"> Czerwony</li>
<li><input type="checkbox" value="blue" checked> Niebieski</li>
<li><input type="checkbox" value="green"> Zielony</li>
</ul>
<select name="selectColors">
<option value="red">Czerwony</option>
<option value="blue" selected="selected">Niebieski</option>
<option value="green">Zielony</option>
</select>
</div>
</body>
如果你想测试此代码,这里是链接(的jsfiddle):https://jsfiddle.net/8yayr972/1/
貌似复选框选择正常工作与父()函数。你有没有想到为什么selectIndex在选择列表更改侦听器不工作?我读过有新的道具(“attr”)功能,但有必要使用它?谢谢你的回答。 – anton86993