我想获得该结构中的所有选项:
<div id='navbar-left'>
<div class='custom-dropdown' />
<div class='custom-dropdown'>
<select class='nav-select hidden'>
<option />
<option/>
</select>
</div>
我试过了:var countries = $('#navbar-left > div[2] > select');
但我没有内容,我做错了什么?
答案 0 :(得分:0)
取决于你真正想要的那些选项......价值还是HTML?
对于值:
$('#navbar-left option').each(function() {
console.log($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='navbar-left'>
<div class='custom-dropdown' />
<div class='custom-dropdown'>
<select class='nav-select hidden'>
<option value="1">One</option>
<option value="2">Two</option>
</select>
</div>
</div>
对于HTML:
$('#navbar-left option').each(function() {
console.log($(this).html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='navbar-left'>
<div class='custom-dropdown' />
<div class='custom-dropdown'>
<select class='nav-select hidden'>
<option value="1">One</option>
<option value="2">Two</option>
</select>
</div>
</div>
现在,如果你想要一个变量 ......我想它应该是一个数组:
var countries = [];
$('#navbar-left option').each(function() {
countries.push($(this).val());
});
console.log(countries); // An array of all the values
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='navbar-left'>
<div class='custom-dropdown' />
<div class='custom-dropdown'>
<select class='nav-select hidden'>
<option value="US">United States of America</option>
<option value="CA">Canada</option>
</select>
</div>
</div>