我想在页面上迭代所有<select>
并到达options
。我使用下面的代码:
$(function(){
$('select').each(function(){
$(this + ' option').each(function(){
//can't access options
});
});
});
我收到错误:
Error: Syntax error, unrecognized expression: [object HTMLSelectElement] [option]
但是此代码有效:
$(function(){
$('select').each(function(i,v){
$.each(v.children(),function(){
//can access options
});
});
});
第一个代码出了什么问题!
使用$(this +' option')
有什么问题?
答案 0 :(得分:4)
选择器中的this
是对象,您在选择器中使用它作为字符串来连接它,您可以在上下文中使用$(this).find
或传递this
。
$(this).find(' option')
或
$(' option', this)
更直接的方法是使用Descendant Selector (“ancestor descendant”)
$('select option').each(
或Child Selector (“parent > child”)喜欢
$('select > option').each
答案 1 :(得分:1)
您可以使用select > option
选择器。
$(function(){
$('select > option').each(function(){
//can access options
});
});
答案 2 :(得分:0)
在这种情况下,你必须像这样使用children()
。
$(function () {
$('select').each(function () {
$(this).children('option').each(function () {
//can access options
});
});
});