【问题标题】:Why can't I clear an input field with javascript?为什么我不能用 javascript 清除输入字段?
【发布时间】:2016-08-15 01:12:23
【问题描述】:

我想清除并更改给定 url 上输入的值。我使用的 js 什么都不做,也不会导致错误。为什么会发生这种情况,我该如何解决?

@Test
public void clearField() throws Exception {
    String url = "https://sfbay.craigslist.org/search/pen/apa?hasPic=1&search_distance=25&" +
            "postal=94014&nh=75&nh=80&min_price=1500&max_price=2500&bedrooms=1&bathrooms=1";
    //url = "https://sfbay.craigslist.org/search/pen/apa?housing_type=1";//Clear & set value works with this url.
    browser.get(url);

    WebElement element = browser.findElement(By.name("search_distance"));
    String char_sequence = "10";

    //Clear the field
    send_keys_v2(element, "");
    //Re write the field
    send_keys_v2(element, char_sequence);
}

public void send_keys_v1(WebElement element, String char_sequence) {
    ((JavascriptExecutor) browser).executeScript("arguments[0].value='" +
            char_sequence + "';", element);
}

public void send_keys_v2(WebElement element, String char_sequence) {
    ((JavascriptExecutor) browser).executeScript("arguments[0].setAttribute=('value', '" +
            char_sequence + "');", element);
}

参考:Set value of input instead of sendKeys() - selenium webdriver nodejs

How can I consistently remove the default text from an input element with Selenium?

【问题讨论】:

    标签: javascript java selenium


    【解决方案1】:

    一个可能且可能的答案是,您在尝试清除的元素之前有另一个同名元素。

    请检查 html 并检查,如果找到多个元素,则采用第一个元素。

    作为替代方案,您可以使用 CSS 选择器,例如:

    .searchInput[name*=search_distance]

    【讨论】:

      【解决方案2】:

      尝试在 Selenium 中使用:

      WebElement.clear()

      void clear() 如果这个元素是一个文本输入元素,这将清除 价值。对其他元素没有影响。文本输入元素是 INPUT 和 TEXTAREA 元素。 More info here.

      【讨论】:

        猜你喜欢
        • 2023-03-31
        • 2021-08-04
        • 1970-01-01
        • 1970-01-01
        • 2016-07-10
        • 1970-01-01
        • 1970-01-01
        • 2022-10-06
        • 2020-11-21
        相关资源
        最近更新 更多