javascript 如何修复 selenium-webriver 错误 - $ 未定义?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28670805/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 09:20:59  来源:igfitidea点击:

How fix selenium-webriver error - $ is not defined?

javajavascriptseleniumgroovyselenium-webdriver

提问by nightmare

I am trying to add an event to a button:

我正在尝试向按钮添加事件:

str = "a#fCoverage" // my locator
def str2 = "$('" + str + "').addEventListener('click', function(){alert('text')});" // add event
js.exec(str2)

But I get this error:

但我收到此错误:

error: org.openqa.selenium.WebDriverException: unknown error: $ is not defined

错误:org.openqa.selenium.WebDriverException:未知错误:$ 未定义

Could anyone help me please?

有人可以帮我吗?

回答by Anish

Use document.querySelectorinplace of $

使用document.querySelector代替$

Your code would end up

你的代码最终会

str = "a#fCoverage" // my locator
def str2 = "document.querySelector('" + str + "').addEventListener('click', function(){alert('text')});" // add event
js.exec(str2)

回答by Arran

addEventListeneris a method on the documentas opposed to $(which is usuallya shorthand for jQuery).

addEventListener是一种方法,而document不是$通常是 jQuery 的简写)。

So change $to document.

所以$改为document.