$ .each()on在页面中选择并获取迭代选项

时间:2016-02-23 11:28:10

标签: jquery

我想在页面上迭代所有<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')有什么问题?

3 个答案:

答案 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
        });
    });
});

FIDDLE DEMO