我有一个包含n个选项的选择列表:
<select id="codeLeft" class="form-control">
{% for code in code %}
<option id="{{ code['try'] - 1}}">#{{ code['try'] }} --- {{ code['date'] }}</option>
{% endfor %}
</select>
现在我有两个按钮,我想用来迭代这个列表(左键按钮上一项和右键下一项)。我已经达到了最后一项,我想再次从底部开始。
$('#button_left').click(function () {
var idCode = $('#codeLeft').children(':selected').attr('id');
var idNext = parseInt(idCode) - 1;
if(idNext < 0){
idNext = codeArray.length - 1;
}
$('#codeLeft option[id=' + idNext + ']').attr("selected", "selected");
});
$('#button_right').click(function () {
var idCode = $('#codeLeft').children(':selected').attr('id');
var idNext = parseInt(idCode) + 1;
if(idNext === codeArray.length){
idNext = 0;
}
$('#codeLeft option[id=' + idNext + ']').attr("selected", "selected");
});
我的问题是这只能工作n次(n是代码长度)。有谁知道为什么?
答案 0 :(得分:0)
首先,您将整数指定为ID,这是不正确的。
Dropdownlist显示已选择属性的第一个属性。因此,当你运行它时,&#34; n&#34;次,所有选项都会将属性选为true,浏览器将不再工作,因为它将当前选项视为已选中。不要将属性设置为选中。相反,使用prop:
$('#codeLeft option[id=' + idNext + ']').prop('selected', true);