2012-09-17 75 views
1

我寫了這個代碼中的每個元素添加attr到已經在index變量定義的值的選項元素:jQuery的:添加ATTR基於值列表

$(document).ready(function(){ 

    $('option').each(function() { 
     var index = '1'; 
     if($(this).attr('value') == index) 
     $(this).attr('selected','selected'); 
    }); 

}); 

如何ATTR添加到具有值列出的每個元素在index變量上。事情是這樣的:

 var index = '1,2,5,8,7,9'; 
     if($(this).attr('value') == index) 
... 

UPDATE: 這是我的html代碼:

<select name="category[]" multiple="multiple" id="category"> 
    <option class="level-0" value="1">Jobs</option> 
    <option class="level-1" value="24">CSS</option> 
    <option class="level-0" value="5">Products</option> 
</select> 

回答

3
$('#category option').each(function() { 
    var index = [1,2,5,8,7,9], 
     value = parseInt(this.value, 10); // convert the value to integer 
    if($.inArray(value, index) >= 0) 
    $(this).attr('selected','selected'); //or, $(this).prop('selected', true); 
}); 

Working sample


沒有陣列

$('#category option').each(function() { 
    var index = '1,2,5,8,7,9', 
     value = this.value; 
    if(index.indexOf(value) >= 0) 
    $(this).attr('selected','selected'); //or, $(this).prop('selected', true); 
}); 

Working sample


使用filter()

var index = '1,2,5,8,7,9'; 
$('#category option').filter(function() { 
    return index.indexOf(this.value) >= 0; 
}).attr('selected', 'selected'); 

Working sample


使用.attr('selected', callback)

var index = '1,2,5,8,7,9'; 
$('#category option').attr('selected', function(i, val) { 
    if(index.indexOf(this.value) >= 0) 
    return 'selected'; 
}) 

Working sample

+0

很好的答案,很多不同的選項。因此,字符串1(及其各種派生類型)不太適用,因爲一個數字可以很容易地成爲另一個數字的子字符串 - 例如'70'包含'7',所以這兩個字符都可以通過,即使只有'70'在列表中。 – nbrooks

2

合併值到一個數組,然後使用原生JS數組indexOf方法:

var index = [1,2,5,8,7,9]; 
if(index.indexOf($(this).val()) > -1) { 
    //... 
} 


要爲多個元素執行此操作,您可以使用 .each()

var index = [1,2,5,8,7,9]; 
$("#category option").each(function() { 
    if(index.indexOf($(this).val()) > -1) { 
     $(this).prop('selected', true); 
    } 
}); 
+0

不行的,我添加HTML代碼到我的問題。 – Nulled

1

你不必遍歷option小號

$("select").each(function(){ 
    var index = $(this).val(); 
    if($.inArray([1,2,5,8,7,9], index) > -1) 
    $(this).prop("selectedIndex", index); //set selected index 
    } 
} 
+0

我試試這個,但不能正常工作,請看看我的代碼 – Nulled

1

隨着select,你可以做通過使用jQuery簡單得多。

你可能只是做:

$("#select-id").val(value); 
// eg: $("#select-id").val('5'); will make the option whose value is 5 to be selected. 

Check the demo.

+0

謝謝,但沒有工作 – Nulled

+0

@NuLLeR檢查我增加了演示。 – xdazz

1

如果你只是想要一個快速的解決方案與您的當前設置與index爲逗號分隔字符串,試試這個:

$(this).prop('selected', 
    (new RegExp('('+index.split(',').join('|')+')')) 
    .test(this.value) 
);