当我点击下一个或上一个按钮时,我有错误。这是我的HTML
$("#nextPage").click(function() {
$('#pagination option:selected').next().attr('selected', 'selected');
console.log("hahaha next");
})
$("#prevPage").click(function() {
$('#pagination option:selected').prev().attr('selected', 'selected');
console.log("prev");
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" value="prev" id="prevPage">
<select id="pagination">
<option value="1" selected>1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
<input type="button" value="next" id="nextPage">
&#13;
谢谢
答案 0 :(得分:5)
使用prop
代替attr
并完善其工作。
$("#nextPage").click(function() {
$('#pagination option:selected').next().prop('selected', 'selected');
console.log("hahaha next");
})
$("#prevPage").click(function() {
$('#pagination option:selected').prev().prop('selected', 'selected');
console.log("prev");
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" value="prev" id="prevPage">
<select id="pagination">
<option value="1" selected>1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
<input type="button" value="next" id="nextPage">
&#13;
答案 1 :(得分:3)
使用.prop
代替.attr
作为.attr
只会为每个选项添加额外属性,而.prop
实际上会更改所选项目
$("#nextPage").click(function() {
$('#pagination option:selected').next().prop('selected', true);
console.log("hahaha next");
})
$("#prevPage").click(function() {
$('#pagination option:selected').prev().prop('selected', true);
console.log("prev");
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" value="prev" id="prevPage">
<select id="pagination">
<option value="1" selected>1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
<input type="button" value="next" id="nextPage">
&#13;