简体   繁体   English

更快选择多个选项值

[英]faster selection of multiple option values

I have a multi-select list-box with 100+ <option> 我有一个100+ <option>的多选列表框

Now I have 7 or 8 values that needs to be selected. 现在,我需要选择7或8个值。

My code is: 我的代码是:

            var selObj = document.getElementById('list1');
            var len = selObj.length;
            var selected_values = '1#2#15#34#82#96';
            var selected_values_array = selected_values.split('#');
            var alen = selected_values_array.length;

            for (i = 0; i < len; i++) {
                for (j = 0; j < alen; j++) {
                    if (selObj[i].value == selected_values_array[j]) {
                        selObj[i].selected = true;
                        break;
                    }
                }
            }

When script is encountered, browser stops responding. 遇到脚本时,浏览器停止响应。 I know my code is bad, but is their any way to improve it. 我知道我的代码很糟糕,但是他们有什么方法可以改善它。 Either using jQuery or javascript? 使用jQuery还是JavaScript?

Thanks 谢谢

How about this with a little help of jQuery (got it working now): 借助jQuery的一点帮助(现在可以正常工作):

var selected_values = '1#2#15#34#82#96';
var selectors = '#list1 > option[value="' + selected_values.split('#').join('"], #list1 > option[value="') + '"]';
$( selectors ).each( function() {
    $( this ).attr( 'selected', true );
} );

A bit uglier than I'd hoped. 比我希望的要丑一些。 But hey. 可是 :) :)

See it in action here . 看到它在这里行动。 And here is an edited version with a larger sized select box. 这是一个带有较大选择框的编辑版本

Try this.. 尝试这个..

$('#list1 option').each(function(i) {   

  for (j = 0; j < alen; j++) {
   if($(this).val() == selected_values_array[j]) {
     $(this).attr("selected", true);   
   }
  }
 }); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM