[英]How to increment the value for an element locator using javascript
I need to grab the element for "n" of rows however the element value increments as below:我需要抓取“n”行的元素,但是元素值递增如下:
<select aria-invalid="false" id="select-fieldName-0-1" class="css-14xtrl2">.
<select aria-invalid="false" id="select-fieldName-0-1-0" class="css-14xtrl2">.
<select aria-invalid="false" id="select-fieldName-0-1-1-0" class="css-14xtrl2">.
<select aria-invalid="false" id="select-fieldName-0-1-1-1-0" class="css-14xtrl2">.
and so on.等等。 How can I grab the element "id" to loop it for "n" number of times?
如何获取元素“id”以将其循环“n”次? Thanks in advance:)
提前致谢:)
i don't know why you're incrementing like that, but if i understand correctly you want to pick the value of all of them.我不知道你为什么要这样增加,但如果我理解正确,你想选择所有这些的值。 Following @happyvirus comment you should do this:
在@happyvirus 评论之后,您应该这样做:
const selectBoxes = document.querySelectorAll('[id^=select-fieldName]');
The ^
means a "starts like". ^
表示“开始喜欢”。
Then you could just loop selectBoxes, pick values, manipulate them, whatever.然后你可以循环选择框,选择值,操作它们,等等。
I haven't found a consistent pattern in the transformation of the first three elements of your example.在您的示例的前三个元素的转换中,我没有找到一致的模式。 If I consider it accurate from the 2nd element then you are able to generate the selectors with the following JavaScript methods:
String.split()
, Array.splice()
, Array.indexOf()
and Array.join()
如果我认为第二个元素是准确的,那么您可以使用以下 JavaScript 方法生成选择器:
String.split()
、 Array.splice()
、 Array.indexOf()
和Array.join()
You can grab a string pattern ( '-0-1-'
) which after you will insert the incrementer string part ( '1-'
).您可以获取一个字符串模式(
'-0-1-'
),然后插入增量字符串部分( '1-'
)。 Note: Array.splice()
is an in-place array method, it is applied directly on the original array.注意:
Array.splice()
是一种就地数组方法,它直接应用于原始数组。
Example (iterated 8 times):示例(迭代 8 次):
let sel ='select-fieldName-0-1-0'
for (let i = 0; i < 8; i++) {
const selArr = sel.split('')
selArr.splice(sel.indexOf('-0-1-') + '-0-1-'.length, 0, '1-')
sel = selArr.join('')
console.log(sel)
}
Output: Output:
select-fieldName-0-1-1-0
select-fieldName-0-1-1-1-0
select-fieldName-0-1-1-1-1-0
select-fieldName-0-1-1-1-1-1-0
select-fieldName-0-1-1-1-1-1-1-0
select-fieldName-0-1-1-1-1-1-1-1-0
select-fieldName-0-1-1-1-1-1-1-1-1-0
select-fieldName-0-1-1-1-1-1-1-1-1-1-0
So if you are inside your main playwright script, then you can use the for
loop to interact with the elements with the above selector pattern:所以如果你在你的主剧本中,那么你可以使用
for
循环与上面选择器模式的元素进行交互:
for (...)
...
await page.click(sel)
}
Place the playwright actions to the right place, eg the 1st iteration should be clicked before the for loop starts if follow my example.将剧作家动作放置在正确的位置,例如,如果按照我的示例,应该在 for 循环开始之前单击第一次迭代。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.