jQuery:如果值在数组中,则在选项中设置“selected”标签

SPi*_*SPi 1 javascript jquery selectedindex

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

我的脚本.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');
   };

});
Run Code Online (Sandbox Code Playgroud)

.js脚本正确enqueqed。

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>
Run Code Online (Sandbox Code Playgroud)

Ror*_*san 5

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

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

示例小提琴