Javascript 默认情况下选择<;中的所有选项;选择>;

Javascript 默认情况下选择<;中的所有选项;选择>;,javascript,php,html,drupal,option,Javascript,Php,Html,Drupal,Option,我需要在为html充电时,默认情况下通过选项列表选择所有选项: 这是我公司代码的一部分 drupal_add_js( " var projects='$projectsEncode'; var narrativeList='$narrativeListEncode'; var outputs='$outputsEncode'; var topoNetwork='$topolog

我需要在为html充电时,默认情况下通过选项列表选择所有选项: 这是我公司代码的一部分

drupal_add_js(
            "
            var projects='$projectsEncode';
            var narrativeList='$narrativeListEncode';
            var outputs='$outputsEncode';
            var topoNetwork='$topologicalNetworkEncode';
            var datasetUuid='$datasetUuid';
            var narrativeCount='$narrativeCount';
            var footprintNid='$footprintLayersEncode';
            ",
            'inline'
        );
这是我在.js中代码的一部分

var narratives = JSON.parse(narrativeList);
var narrativeDropdown = $("#narrativeMode");
narratives.forEach(function (narrative) {
narrativeDropdown.append('<option value=' + narrative.nid + '> 
 Narrativa ' + narrative.name + '</option>');
  });
var elements = document.getElementById("narrativeMode").options;
console.log("Elementos cargados:",elements)
for(var i = 0; i < elements.length; i++){
 elements[i].selected= true;

}
var descriptions=JSON.parse(叙事列表);
var叙事下拉菜单=$(“#叙事模式”);
叙述。forEach(功能(叙述){
叙述性下拉列表。附加('
叙事A'+叙事。名称+'';
});
var elements=document.getElementById(“叙述模式”).options;
log(“Elementos cargados:”,elements)
对于(var i=0;i
这是html

<select class="mi-selector custom-select" multiple='multiple' data-style="form-control" data-live-search="true" title="-- Seleccione mínimo 1--" id="narrativeMode">

        </select>


感谢您的帮助

您的代码不起作用,因为您正在比较所选的
而不是属性

更改此项:

for(var i = 0; i < elements.length; i++){
  elements[i].selected== true; // Note the use of == here
}
for(var i=0;i
为此:

for(var i = 0; i < elements.length; i++){
  elements[i].selected = true; // Note the use of single = here
}
for(var i=0;i
您正在比较值,而不是设置值:

elements[i].selected == true;
使用:

工作示例:

var叙事下拉列表=$(“#叙事模式”);
var elements=document.getElementById(“叙述模式”).options;
log(“Elementos cargados:”,elements)
对于(var i=0;i

1.
2.
3.

我将“==”改为“=”,但不修复我的选项列表是dinamic,我在中用新的代码片段更新帖子。我回答的要点是使用单
=
而不是双。
elements[i].selected = true;