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

时间:2022-06-20 02:04:50

Is there any way to Optimize the below lines of code?

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

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

I have tried adding all the fields by comma seperated, but it is not working.

我尝试用逗号分隔添加所有字段,但它不起作用。

Please help to optimize the above code.

请帮助优化上面的代码。

4 个解决方案

#1


1  

I would try something like :

我会尝试类似的东西:

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

or like this :

或者像这样:

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

at last (but I wouldn't call it optimization ;-)

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

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

#2


0  

Try

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

Its possible to have multple elements in the selector.

它可能在选择器中有多个元素。

#3


0  

add the same class to all of the above and refer to it once instead of referring to the ID's multiple times

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

#4


0  

The following should do (see also jQuery multiple-selector api)

以下应该做(另请参阅jQuery多选择器api)

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

#1


1  

I would try something like :

我会尝试类似的东西:

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

or like this :

或者像这样:

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

at last (but I wouldn't call it optimization ;-)

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

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

#2


0  

Try

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

Its possible to have multple elements in the selector.

它可能在选择器中有多个元素。

#3


0  

add the same class to all of the above and refer to it once instead of referring to the ID's multiple times

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

#4


0  

The following should do (see also jQuery multiple-selector api)

以下应该做(另请参阅jQuery多选择器api)

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