2016-02-28 136 views
0

我有一個選擇元素與一個巨大的選項列表(超過2000)。如何獲取選擇元素的所有選項的值和文本

我想逐個獲取每個選項的值和名稱。

<select name='county_city' id='county_city'> 
    <OPTION value="51421">City one</OPTION> 
    <OPTION value="51422">City two</OPTION> 
    <OPTION value="51423">City three</OPTION> 
    <OPTION value="51424">City four</OPTION> 
</select> 

我想是,每行

51421 = City one 
51422 = City two 
51423 = City three 
51424 = City four 

一個選項..

感謝。

回答

0

首先,你需要通過option列數組進行迭代,並收集值&文成數據陣列,那麼你可以做任何你覺得喜歡它,比如它打印到頁面像這樣:

var data = []; 
 
$('#county_city option').each(function(){ 
 
    var current = $(this); 
 
    data.push({ 
 
    value: current.val(), 
 
    text: current.html() 
 
    }) 
 
}); 
 

 

 
$.each(data, function(){ 
 
    console.log(this); 
 
    $('#result').append(this.value + ': ' + this.text) 
 
       .append('<br />'); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<select name='county_city' id='county_city'> 
 
<OPTION value="51421">City one</OPTION> 
 
<OPTION value="51422">City two</OPTION> 
 
<OPTION value="51423">City three</OPTION> 
 
<OPTION value="51424">City four</OPTION> 
 
</select> 
 

 
<div id="result"></div>

1

var options = document.querySelectorAll('select[name="county_city"] option'); 
 
var data = Array.prototype.map.call(options, function(elem) { 
 
    return {text: elem.textContent, value: elem.value}; 
 
}); 
 

 
document.write("<pre>" + JSON.stringify(data, null, "\t"));
<select name='county_city' id='county_city'> 
 
<OPTION value="51421">City one</OPTION> 
 
<OPTION value="51422">City two</OPTION> 
 
<OPTION value="51423">City three</OPTION> 
 
<OPTION value="51424">City four</OPTION> 
 
</select>

0

使用下面的代碼: -

HTML

<select name='county_city' id='county_city'> 
<OPTION value="51421">City one</OPTION> 
<OPTION value="51422">City two</OPTION> 
<OPTION value="51423">City three</OPTION> 
<OPTION value="51424">City four</OPTION> 
</select> 

JQuery的

$(document).ready(function() { 
    $("#county_city OPTION").each(function(index){ 
alert(this.value); 
alert(this.text); 
    }); 
}); 
相關問題