如何使用jquery在多个选择列表中选择多个选项?

在我的Web应用程序中,一个方法返回一个数组列表,其中包含必须选择的选择选项的ID。 很难使用DOM方法选择它们。

有没有办法使用jQuery来做到这一点。

任何建议都会更加赞赏……

提前致谢!!!

编辑:根据您的评论,您的数据看起来如下代码。

有一个问题。 HTML ID属性以数字开头无效。 ID必须以字母开头。

无论如何,我会告诉你解决方案,但你应该修复ID。

var array = [{respID:1, respName:null}, {respID:2, respName:null}, {respID:3, respName:null}, {respID:4, respName:null}, {respID:5, respName:null} ]; $.each(array, function(i,val) { $('#' + val.respID).attr("selected", "selected"); }); 

现在,这将在循环的每次迭代中为您提供respID的值。

但同样,HTML ID不能以数字开头。 我建议将HTML ID属性更新为id_5而不是5

  

然后你会这样做:

 $.each(array, function(i,val) { $('#id_' + val.respID).attr("selected", "selected"); }); 

使用jQuery,您可以在元素集合上调用attr("selected", true) 。 您所要做的就是选择正确的选择器:

 $('#opt1, #opt2, #opt3').attr("selected", true); 

http://api.jquery.com/attr/

它实际上非常简单,您需要做的就是将所选属性添加到您想要的元素中。

 $("#id1, #id2", "select").attr("selected", "selected"); 

您也可以按值过滤它们

 $("option[value=someText]", "select").attr("selected", "selected"); 

如果ids是一个ID数组,则以下代码应该有效:

 $.each(ids, function() { $("#" + this).attr("selected", true); });