通过javascript功能选择选择的选项

问题描述 投票:0回答:1

我一直在尝试实施一个解决方案,在 如何在jQuery的SELECT元素中选择特定的选项? 毫无用处。 要么是添加了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 "的选项中 在 "selected "属性的上方

      //$('#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(在'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);
        }
    });
} 
javascript jquery dom jquery-chosen
1个回答
1
投票

你不需要css选择器周围的单引号。

$(`${target} option[value="${optionValue}"]`).attr('selected', 'selected');
© www.soinside.com 2019 - 2024. All rights reserved.