为什么我无法使用javascript清除输入字段?

问题描述:

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

@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]

尝试在硒的使用方法:

WebElement.clear()

无效明确()如果此元素是一个文本输入元件,这将清除 的值。对其他元素没有影响。文本输入元素是 INPUT和TEXTAREA元素。 More info here