无法使用javascript在html中设置所选索引

无法使用javascript在html中设置所选索引,javascript,Javascript,这是我的Javascript: var productId=this.dataset.product var action=this.dataset.action var a = document.getElementById(productId); var size = a.options[a.selectedIndex].value; var l = toString(document.getElementById(productId).selecte

这是我的Javascript:

    var productId=this.dataset.product
    var action=this.dataset.action
    var a = document.getElementById(productId);
    var size = a.options[a.selectedIndex].value;
    var l = toString(document.getElementById(productId).selectedIndex);
    a.selectedIndex=l;
    updateUserOrder(productId, action, size)
在这种情况下,我能够正确地获取productId、action、a、size、l,但无法设置此后选择的索引。当我的网站上的用户单击“添加”按钮时,产品将以正确的大小添加到购物车中,并且页面将刷新。但是,正如在我的代码中尝试的那样,所选选项不会按我希望的那样更改,而是保持默认值(index=0)

这是我的html供参考:

<select class="selection-2 border" data-product={{product.id}}
               style="border: cadetblue;" name="size" id="{{product.id}}">
              
                <option value="S" id="S">S</option>
                <option value="M" id="M">M</option>
                <option value="L" id="L">L</option>
              
              </select>

s
M
L

我总结的问题是,例如,一个用户选择了一个位于第二个索引的选项,然后在页面刷新之后(当我的代码执行时)选择框应将默认选项显示为当前未出现的带有第二个索引的选项。

您是否可以将模板代码替换为生成的
,并将其转换为可运行的代码片段以演示?@David我已将选项设置为代码执行时的外观。页面后,更改不会持久它被刷新了。如果您想记住他们在刷新之间所做的选择,请将其放入
localStorage
,然后在页面重新加载时重新分配。@VATSALJAIN,如果您以某种方式存储购物车,则意味着信息已经以跨页面可用的方式存在。因此,在用于收回购物车的代码中,只需在购物车中找到该尺寸,并在显示select选项的循环中,使用if语句,说明存储的尺寸是否相同,将
selected
添加到该选项。@VATSALJAIN,我不知道您正在使用的模板的语法/功能,也不知道变量结构,但这是一个伪代码,您可以用作指导:
{%for t in product.size.all%}if({{t}==product.size){selected=“selected”}else{selected=”“}{{t}{endfor%}