微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么我不能使用javascript清除输入字段?

我想清除&更改给定网址上的输入值.我使用的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?

解决方法:

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

请检查html并检查是否找到多个元素,然后采用第一个.

或者,您可以使用css选择器,例如:

.searchInput[name*=search_distance]

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐