【问题标题】:Changing selected value in a select option更改选择选项中的选定值
【发布时间】:2020-07-27 06:22:16
【问题描述】:

我目前无法更改下拉列表的值。我目前正在https://www.reebok.com/us/cart 上将商品添加到我的购物车中。我正在尝试更改数量。

我正在尝试将我的 java 代码重写为 javascript。话虽如此。

Select select = new Select(driver.findElement(By.xpath("//* [@id=\"app\"]/div/div/div/div/div[2]/div/main/div[1]/div/div/div/div/div/div[2]/div[2]/div[2]/div/div/select")));
select.selectByVisibleText(5);

目前使用 Selenium 库在 java 中为我工作。但是在 Javascript 中,我无法模拟相同的步骤。我什么都试过了。

编辑:我试过了

var select= document.evaluate('//*[@id="app"]/div/div/div/div/div[2]/div/main/div[1]/div/div/div/div/div/div[2]/div[2]/div[2]/div/div/select', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
select.selectedIndex=7;

document.getElementsByClassName('gl-dropdown-native__select-element')[0].value=7;

【问题讨论】:

  • 你具体用的是什么?请分享您无法按预期工作的代码
  • 设置 value 将不起作用 - 您必须设置 selectedIndex
  • 还是不行。
  • 你也必须触发事件。我似乎无法弄清楚它正在听什么事件。所以在你做.value = 6; 之后你需要再做.dispatchEvent(new Event('change')); 但是我不知道它在听什么事件。我什至没有喜悦地尝试“点击”......但是当我显示隐藏的选择下拉菜单时,我可以看到值发生变化。它只是不会触发更改:/
  • 是的,我猜Java selectByVisibleText() 方法会自动执行此操作?

标签: javascript dropdown


【解决方案1】:

这是改变购物篮中物品的工作功能。问题是找到他们所依赖的处理程序和事件类型。是mouseup 和直接在窗口中的事件。

function changeItemTo(itermNumber) {
    const itemsSelector = '.gl-dropdown-custom__options button';
    const itemsElements = document.querySelectorAll(itemsSelector);
    if (itemsElements == null) throw new Error(`Selector ${itemsSelector} is wrong, nothing found`);
    const buttonForItem = itemsElements[itermNumber];
    if (buttonForItem == null) throw new Error(`Item with index: ${itermNumber} not found`);

    buttonForItem.dispatchEvent(new Event('mouseup', { bubbles: true, cancelable: true, }));
}

希望这会有所帮助!

【讨论】:

  • 仍然对我不起作用。我在 reebok 网站上,并试图在我的购物车中有商品时更改数量。我编辑了类以反映锐步网站上的选择元素。 const select = document.querySelector('.gl-dropdown-custom__select-element');select.selectedIndex = 2;select.dispatchEvent(new Event('change'));
  • 很有意思,我去看看)
  • 再问一个问题,你是怎么发现它依赖的是mouseup
  • 实际上是硬调试。我发现点击事件被忽略并查看应用程序代码。幸运的是,他们非常慷慨地提供了地图文件,因此不需要太多时间
  • 在哪里可以找到地图文件?
猜你喜欢
  • 2020-10-20
  • 1970-01-01
  • 2021-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-05
  • 1970-01-01
  • 2014-01-12
相关资源
最近更新 更多