为什么我不能用javascript清除输入字段? [英] Why can't I clear an input field with javascript?

查看:78
本文介绍了为什么我不能用javascript清除输入字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to clear & change the value of an input on the given url. The js I used does nothing and causes no errors. Why is this happening and how do I fix it ?

@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);
}

参考文献:设置输入值而不是sendKeys() - selenium webdriver nodejs

如何使用Selenium从输入元素中一致地删除默认文本?

推荐答案

一种可能的和可能的答案是你在要清除的元素之前有另一个具有相同名称的元素。

One possible and probable answer is that you have another element with the same name before the one that you are trying to clear.

请检查html并检查,如果找到多个元素,那么第一个元素一个被带走。

Please inspect the html and check, if multiple elements found then the first one is taken.

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

As an alternative you can use a css selector like:

.searchInput[name*=search_distance]

这篇关于为什么我不能用javascript清除输入字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆