2010-04-26 153 views

回答

3

在普通的JavaScript:

function in_array(needle, haystack, argStrict) 
{ 
    var key = '', strict = !!argStrict; 
    if (strict) 
    { 
     for (key in haystack) 
     { 
      if (haystack[key] === needle) 
       return true; 
     } 
    } 
    else 
    { 
     for (key in haystack) 
     { 
      if (haystack[key] == needle) 
       return true; 
     } 
    } 
    return false; 
} 

var values = new Array(1, 2, 4); 
var select = document.getElementById('selectName'); //Change to the id of the select 
if (select) 
{ 
    for (var i = 0; i < select.options.length; i++) 
    { 
     //Select options matching array values, unselect others 
     select.options[i].selected = in_array(select.options[i].value, values, false); 
    } 
} 

UPDATE:新增的JavaScript函數in_array模仿PHP一個...

+0

您將通過選擇項目的整個集合循環?你不是過度的嗎? – 2010-04-26 17:51:36

+0

是的,這有點矯枉過正,但是因爲選擇中的許多元素可以具有相同的值......這是不太可能的,但它是可能的:)無論如何,這個片段我想你會明白如何去做。 – AlexV 2010-04-26 17:57:39

+0

我不認爲開發者應該允許與其他值相同的選擇,這將是可維護性地獄。 – 2010-04-26 18:02:58

0

我不是很熟悉JavaScript,但我認爲那就是:

var values = [1, 2, 4]; 
var sel = document.getElementsByTagName('SELECT')[0]; 
for (var i = 0; i < sel.options.length; i++) { 
    if(sel.options[i].value == 1 || sel.options[i].value == 2 || sel.options[i].value == 4) 
     sel.options[i].selected = 'selected'; 
} 
1

由於我還沒有50個代表點我不能評論或修復上面的帖子

因此,這裏是我的修復上述陣列

var values = new Array(1, 2, 4); // using commas 
var values = [1, 2, 4]; // using array notation 
+0

- 啊,他自己修好了... – mplungjan 2010-04-26 17:52:10

+1

但哈門是錯的。 您無法使用您發佈的值在其索引中選擇一個選項 – mplungjan 2010-04-26 17:53:20

6

jQuery有一個名爲$.inArray(value,array)工具。你可以做這樣的事情:

var array = [1,2,4]; 

$('#example option').each(function() { 
    var $th = $(this); 
    var value = parseInt($th.val()); 
    if($.inArray(value,array) >= 0) { 
     $th.attr('selected','selected'); 
    } 
}); 

$.inArray()返回,如果它被發現,或-1,如果它不是數組中值的索引。這就是爲什麼你需要測試>= 0

陣列上的每個值查看示例這裏 -

http://jsfiddle.net/PJs37/