通过jQuery选择上一个和下一个选项

时间:2017-03-31 10:46:54

标签: javascript jquery select html-select

当我点击下一个或上一个按钮时,我有错误。这是我的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;
&#13;
&#13;

Here is my jsfiddle

谢谢

2 个答案:

答案 0 :(得分:5)

使用prop代替attr并完善其工作。

&#13;
&#13;
$("#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;
&#13;
&#13;

答案 1 :(得分:3)

使用.prop代替.attr作为.attr只会为每个选项添加额外属性,而.prop实际上会更改所选项目

&#13;
&#13;
$("#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;
&#13;
&#13;