有没有办法通过javascript注入自动选择HTML<选项>

Is there a way to select HTML <option> automatically with a javascript injection?

本文关键字:HTML 选择 选项 注入 javascript 有没有      更新时间:2023-09-26

假设我在网页上有一个包含此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");