我正在使用一个 wordpress 插件,它强制我使用 name=""属性。所以我无法将其更改为 id=""或 class=""。当我单击按钮时,我希望 name="select"的 selectedIndex 更改为 2。
这是我尝试过的:
<select name="select">
<option value="1">option1</option>
<option value="2">option2</option>
</select>
<input type="button" value="CHANGE" onclick="selectFunction()" />
var selectFunction = function() {
document.getElementById("select").selectedIndex = 2;
};
所以我基本上想使用 name=""而不是 id=""来使用这个函数。这意味着类似 document.getElementById("select").selectedIndex = 2;不会工作。
提前致谢!
最佳答案
您可以使用querySelector()
使用 CSS 样式选择器进行选择:
document.querySelector('select[name="select"]').selectedIndex = 2;
或者,如果您需要支持没有 querySelector()
的旧版 IE,您可以使用 document.getElementsByTagName("select")
然后循环生成的列表会测试每个列表的 .name
,直到找到正确的列表。
或者有 document.getElementsByName()
function ,它也返回一个列表(或 HTMLCollection),但根据 QuirksMode.org它在 IE<=9 中无法正常工作。
请注意,选项索引从 0 开始(因此在您的示例中,您不想将 selectedIndex
设置为 2,因为最后一个选项是索引 1)。
关于Javascript 通过名称更改 Select 的 selectedIndex,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22270562/