循环遍历javascript对象中的选项

时间:2010-11-17 14:01:59

标签: javascript jquery

我有一个包含选择列表的javascript对象。我想循环选择中的所有选项。我正在尝试以下方法:

$(this+' .form-select option').each(function() { console.log(this); });

它的console.log显示它包含选项,但 all 页面上的选项元素不是我传递给它的选项。

我收到以下错误“Uncaught Syntax error,unrecognized expression:[object Object]”

任何帮助都会很棒。

2 个答案:

答案 0 :(得分:1)

使用.find(),如下所示:

$(this).find('option').each(function() { console.log(this); });

this是一个对象,因此您无法在字符串中使用它,但您可以使用它来查找其他元素relatively。如果this已经是jQuery对象,只需执行:

this.find('option').each(function() { console.log(this); });

答案 1 :(得分:0)

我猜测this不是带有选择器的字符串,在这种情况下你的语句无效。我的猜测是你的jQuery选择器应该是这样的:

$('.form-select option', $(this)).each(function(){
    console.log(this);
});