在优化以下jquery代码方面需要帮助

时间:2012-12-03 14:19:23

标签: jquery

有没有办法优化下面的代码行?

        $('#state').children('option:not(:first)').remove();
        $('#city').children('option:not(:first)').remove();
        $('#branch').children('option:not(:first)').remove();
        $('#branchAddress').children('option:not(:first)').remove();

我尝试用逗号分隔添加所有字段,但它无法正常工作。

请帮助优化上述代码。

4 个答案:

答案 0 :(得分:1)

我会尝试类似的事情:

$('#state, #city, #branch, #branchAddress')
    .each(function(i,item){$('option:not(:first)',$(item)).remove();});

或者像这样:

$('#state, #city, #branch, #branchAddress').find('option:not(:first)').remove();

最后(但我不称之为优化; - )

$('#state option:not(:first), #city option:not(:first), #branch option:not(:first), #branchAddress option:not(:first)').remove();

答案 1 :(得分:0)

尝试

$('#branchAddress #state #city #branchAddress').children('option:not(:first)').remove();

选择器中可以有多个元素。

答案 2 :(得分:0)

将相同的类添加到上述所有内容并引用一次而不是多次引用ID

答案 3 :(得分:0)

以下情况应该做(另见jQuery multiple-selector api

$('#state, #city, #branch, #branchAddress').children('option:not(:first)').remove();