jQuery:如果value在数组中,则在选项中设置'selected'标记

时间:2014-04-22 08:52:05

标签: javascript jquery selectedindex

我尝试使用jQuery(在Wordpress网站上)将selected属性添加到option标记。应选择的值存储在PHP数组中。为什么selected属性未添加到<option>..

我-的script.js

jQuery("#location option").each(function($){

var arr = [<?php echo '"'.implode('","', $php_array).'"' ?>];
// for testing also hardcoded array: doesn't work either
// var arr = ["1", "2"];

   if(jQuery.inArray($(this).val(),arr) != -1){
     $(this).attr('selected', 'selected');
   };

});

.js脚本已正确加入。

HTML输出

   <select name="location[]" multiple="multiple" id="location" class="postform" style="display: none;">
            <option value="-1">Select a location</option>
            <option class="level-0" value="1">Location A</option>
            <option class="level-0" value="2">Location B</option>
            <option class="level-0" value="3">Location C</option>

        </select>

2 个答案:

答案 0 :(得分:4)

问题是因为您无法将任何内容传递给each处理程序。从中删除$,您的代码可以正常运行:

var arr = ["1", "2"];
jQuery("#location option").each(function () {
    if (jQuery.inArray($(this).val(), arr) != -1) {
        $(this).prop('selected', true);
    };
});

Example Fiddle

答案 1 :(得分:0)

我认为你在jQuery循环中有拼写错误

jQuery("#location option").each(function($){

var arr = [<?php echo '"'.implode('","', $php_array).'"' ?>];
// for testing also hardcoded array: doesn't work either
// var arr = ["1", "2"];

   if(jQuery.inArray($(this).val(),arr) != -1){
     $(this).attr('selected', 'selected');
   };

});

function($)应该没有参数,比如这个函数()

工作代码:

jQuery("#location option").each(function(){

var arr = [<?php echo '"'.implode('","', $php_array).'"' ?>];
// for testing also hardcoded array: doesn't work either
// var arr = ["1", "2"];

   if(jQuery.inArray($(this).val(),arr) != -1){
     $(this).attr('selected', 'selected');
   };

});

我的jsFiddle:http://jsfiddle.net/Cs329/