我尝试使用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>
答案 0 :(得分:4)
问题是因为您无法将任何内容传递给each
处理程序。从中删除$
,您的代码可以正常运行:
var arr = ["1", "2"];
jQuery("#location option").each(function () {
if (jQuery.inArray($(this).val(), arr) != -1) {
$(this).prop('selected', true);
};
});
答案 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/