简体   繁体   English

Java语言运行到Java中:如何将Java变量传递给代码段JavaScript?

[英]Javascript running into java : How to pass a java variable to a snippet javascript?

I want to pass a java variable to a snippet javascript from a java code. 我想将Java变量从Java代码传递到代码段javascript。 Please how could i perform that? 请问我该怎么执行呢?

For example, From java i want to pass a java variable named 'index' to a snippet javascript like this 例如,我想从Java中将名为“ index”的Java变量传递给像这样的代码段javascript

WebElement element = (WebElement) ((JavascriptExecutor)driver).executeScript("myJavascript.js") 

where myJavascript.js is this one: 其中myJavascript.js是这样的:

var index=arguments[1]; return $('.title')[index];

I have been inspired by the site http://docs.seleniumhq.org/docs/03_webdriver.jsp#introducing-the-selenium-webdriver-api-by-example to write below code which does not work out: 我受到网站http://docs.seleniumhq.org/docs/03_webdriver.jsp#introducing-the-selenium-webdriver-api-by-example的启发而编写了下面无法解决的代码:

int index=0;

for(int index = 0; index < counter; index++){

         WebElement element = (WebElement) ((JavascriptExecutor)driver).executeScript("var index=arguments[1]; return $('.title')[index];");
         System.out.println(element.getText());
    }

This above code works fine when i set values of the index to 0,1,2,....But I want to get it each time from the current value of loop 'for' from java. 当我将索引的值设置为0,1,2,....时,以上代码可以正常工作,但是我想每次从java的'for'循环的当前值获取它。

Thanks. 谢谢。

If I get your question correctly, you need to do this: 如果我正确回答了您的问题,则需要执行以下操作:

WebElement element = (WebElement) ((JavascriptExecutor)driver).executeScript("var index=arguments[1]; return $('.title')["+index+"];");
System.out.println(element.getText());

Basically you need to make sure that "index" value is taken from loop variable - pay attention where the double quotes are in the above. 基本上,您需要确保“索引”值取自循环变量-注意上面双引号的位置。

This should work: 这应该工作:

for(int index = 0; index < counter; index++){
             WebElement element = (WebElement) ((JavascriptExecutor)driver).executeScript("return $('.title')[" + index + "];");
             System.out.println(element.getText());
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM