获取选择列表的前2个html值

时间:2019-03-08 20:45:07

标签: javascript jquery html

有没有办法像下面示例中那样仅选择前2个选择值选项而不是全部4个?我需要

<option value="volvo">Volvo</option>
<option value="saab">Saab</option> 

单击按钮。

 $("#btnTest").click(function(){
     var options = $("#test").html();
     console.log(options);
}); 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<select id="test">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

<button id="btnTest" type="button">Click Me!</button>

2 个答案:

答案 0 :(得分:1)

您可以为此使用options属性

 $("#btnTest").click(function(){
     var options = Array.from($("#test")[0].options).slice(0, 2);
   console.log(options)
}); 

$("#btnTest").click(function() {
  var options = Array.from($("#test")[0].options).slice(0, 2);
  console.log(options)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<select id="test">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

<button id="btnTest" type="button">Click Me!</button>

答案 1 :(得分:1)

您可以使用jQuery :lt()选择器仅获取前两个元素,并链接一个.toArray()以将其转换为HTML数组。

var $options = $("#test option:lt(2)").toArray();

 $("#btnTest").click(function(){
   var options = $("#test option:lt(2)").toArray();
   console.log(options);
 }); 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<select id="test">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

<button id="btnTest" type="button">Click Me!</button>

或者,作为字符串...

var options = $("#test option:lt(2)")
  .toArray()
  .map(function(e){return e.outerHTML})
  .join("\n");

$("#btnTest").click(function(){
  var options = $("#test option:lt(2)")
    .toArray()
    .map(function(e){return e.outerHTML}) //get outerHTML of each element
    .join("\n");                          //join them with a line-break
  console.log(options);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<select id="test">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

<button id="btnTest" type="button">Click Me!</button>