首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >无法使用Jsoup Formelement设置选择选项HTML

无法使用Jsoup Formelement设置选择选项HTML
EN

Stack Overflow用户
提问于 2018-07-28 23:31:00
回答 2查看 623关注 0票数 2

尝试使用JSOUP fromelement在html中设置select选项,但没有成功。

代码语言:javascript
复制
<select name="gender" id="gender" class="textfield" required="true">
<option value=""
>Select</option>
<option value="2">Male</option>
<option value="1">Female</option>
<option value="3">Other</option>
</select>

用于在上述选择选项中设置性别的Jsoup表单元素:

代码语言:javascript
复制
Element gender = loginForm.select("#gender").first();
        gender.attr("Male","2");

如果有人知道怎么做,请让我知道,谢谢。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-07-29 02:21:18

评论中的解释:

代码语言:javascript
复制
    String html = "<select name=\"gender\" id=\"gender\" class=\"textfield\" required=\"true\">"
            + "<option value=\"\">Select</option>"
            + "<option value=\"2\">Male</option>"
            + "<option value=\"1\">Female</option>"
            + "<option value=\"3\">Other</option>"
            + "</select>";

    Document doc = Jsoup.parse(html);

    // getting all the options
    Elements options = doc.select("#gender>option");

    // optional, listing of all options
    for (Element option : options) {
        System.out.println("label: " + option.text() + ", value: " + option.attr("value"));
    }

    // optional, find option with attribute "selected" and remove this attribute to
    // deselect it; it's not needed here, but just in case
    Element selectedOption = options.select("[selected]").first();
    if (selectedOption != null) {
        selectedOption.removeAttr("selected");
    }

    // iterating through all the options and selecting the one you want
    for (Element option : options) {
        if (option.text().equals("Male")) {
            option.attr("selected", "selected"); // select only Male
        }
    }

    // result html with selected option:
    System.out.println(doc.body());
票数 0
EN

Stack Overflow用户

发布于 2018-07-28 23:33:50

您需要设置要选择的选项的selected属性。有关完整的示例,请参阅此答案:

Jsoup POST: Defining a selected option to return HTML?

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51572776

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档