【发布时间】:2020-05-04 20:39:13
【问题描述】:
我一直在尝试实施How do you select a particular option in a SELECT element in jQuery? 中提出的解决方案,但无济于事。将 Chosen 添加到组合中会使解决方案无效,或者我犯了一些超出我的编译器和我无法找到的编码错误。
我的html:
<select name="superType" class="chosen-select chosen-select-creation-allowed" id="superType" style="width: 300px; display: none;" onchange="loadInheritance()" multiple="">
<option style="padding-left:20px;" value=""></option><option style="padding-left:0px" value="28">concept</option>
<option style="padding-left:20px" value="30">human</option>
</select>
当我在此之后放置以下内容时,我希望其中一个将添加到“已选择”属性上方的 value="30" 选项:
//$('#superType option[value="30"]').prop('selected', true);
$('#superType option[value="30"]').attr('selected', 'selected');
$('.chosen-select').trigger("chosen:updated");
相反,根据 DOM 模型检查器和视觉呈现,没有任何反应。
我想要的是让这个选择发生在一个函数中,但是当我尝试构建对上面选项的引用时,我得到了错误:
Syntax error, unrecognized expression: '#superType option[value="30"]'
这是生成的 javascript (procs on 'cid'):
//now go back through and select the ones this CommonNoun already had from before
$.ajax({
url: '/BackToTech/server?function=getExistingSuperTypes',
type: 'POST',
success: function (response){
// var target = $("#superType");
var target = "#superType";
selectOptions(response, target, 0);
$('.chosen-select').trigger("chosen:updated");
}
});
...
function selectOptions(obj, target) {
var concepts = obj;
$.each(concepts, function(concept, value) {
alert(concept, value);
if (concept == "cid") {
optionValue = obj[concept].oid;
$("'" + target + " option[value=\"" + optionValue + "\"]'").attr('selected', 'selected');
} else {
selectOptions(value, target);
}
});
}
【问题讨论】:
-
为什么你的 CSS 选择器周围有单引号?
标签: javascript jquery dom jquery-chosen