有没有办法通过javascript注入自动选择HTML<选项>
Is there a way to select HTML <option> automatically with a javascript injection?
假设我在网页上有一个包含此HTML的表单
<form id="form" method="post">
<select id="selectThis">
<option id="one" value="1">1</option>
<option id="two" value="2">2</option>
<option id="three" value="3">3</option>
<option id="four" value="4">4</option>
</select>
<a href="gothispage.com" onclick="ajaxSubmitFunction('submit') id="submit">submit</a>
</form>
有没有办法注入一个基本上可以做到这一点的 js 代码。
function selectOption(option) {
var a = document.getElementById(option);
a.selected = selected;
if (a === "selected") {
document.getElementById("submit").click();
}
}
selectOption("four");
这是思考如何解决这个问题的正确方法吗?
这不是一个标准的方法,但它有效。你基本上已经在那里了,你只需要整理一些语法:
function selectOption(option) {
var a = document.getElementById(option);
a.selected = true;
// this if statement isn't really needed as you just set it
if (a.selected === true) {
document.getElementById("submit").click();
}
}
selectOption("four");
示例 JsFiddle
更常见的方法是:
function selectOption(option) {
var a = document.getElementById('selectThis');
a.value = option;
document.getElementById("submit").click();
}
selectOption("4");
获取option
元素 id
然后将其value
分配给select
元素:
function selectOption(option) {
var selectedValue = document.getElementById(option).value;
document.getElementById("selectThis").value = selectedValue;
// ...
}
selectOption("four");
演示:http://jsbin.com/sewowenugu/1/edit?html,js,output
试试这个(jQuery):
$("#selectThis").val("4");
相关文章:
- 从动态创建的html选择中选择所选选项
- 向html选择元素添加选项
- HTML选择,在DOM中选择了正确的选项,但在firefox中显示了错误的项目
- 构建HTML选择字段并使用JavaScript数组选择选项
- 当html选择/选项发生更改时,需要更新输入字段
- 使用javascript和html选择第二个选项后发出警报
- javascript函数将当前时间显示为html选择标记的预选值
- laravel5.0中HTML选择标记的动态选择
- jQuery将输入集中在下一个tr->td时,td包含一个输入字段,但从不关注html选择
- 基于's是在HTML选择框中选择的
- 如何使用Angular 2设置HTML选择值
- 在html选择中显示AJAX成功JSON值
- 使用 jQuery 增加 HTML 选择框的大小属性
- 当我认为它不应该重新渲染视图时,如何防止 Meteor 在 html 选择 dom 单击事件上重新渲染视图
- HTML 选择元素的只读等效项
- 如何使 html 选择选项在 Meteor 中工作
- 当“不相关”的 html 选择元素没有选择任何选项时,如何退出 jQuery 事件
- HTML选择:将默认值设置为给定值,而不是从选项列表中选择
- html选择-范围为0-10
- 是否可以在HTML选择下拉菜单的每个选项上附加一个qtip2工具提示