Javascript 如何使用ChereIO填充选项值列表的索引号?
嗨,伙计们,我正在尝试使用cheerio从网站上获取列表的索引号。例如,“40-只剩下一个”的索引号是2 如果只剩下“40”(没有剩下一个),我将如何获得数字2Javascript 如何使用ChereIO填充选项值列表的索引号?,javascript,node.js,cheerio,Javascript,Node.js,Cheerio,嗨,伙计们,我正在尝试使用cheerio从网站上获取列表的索引号。例如,“40-只剩下一个”的索引号是2 如果只剩下“40”(没有剩下一个),我将如何获得数字2 选择大小 40-只剩下一个 41-只剩下一个了 42-只剩下一个 您可以首先使用cheerio/jQuery选择器:contains通过文本选择(文本可以是任何内容),然后调用函数index以获取其父级中的索引: var index = $("option:contains('40')").index(); 注意:函数index返回从
选择大小
40-只剩下一个
41-只剩下一个了
42-只剩下一个
您可以首先使用cheerio/jQuery选择器:contains通过文本选择
(文本可以是任何内容),然后调用函数index
以获取其父级中的索引:
var index = $("option:contains('40')").index();
注意:函数index
返回从0开始的0索引结果,如果需要1索引结果,只需将1添加到其中即可
演示(使用jQuery,cheerio基于jQuery):
var index=$(“选项:包含('40')”).index();
控制台日志(索引)代码>
选择大小
40-只剩下一个
41-只剩下一个了
42-只剩下一个
您可以尝试以下方法:
function getindex(searchValue) {
// you probably want to have a class for them OR pass an array of options
// to this function, because your html might have options in other places
const inner = document.body.getElementsByTagName('option');
for (let i = 0; i < inner.length; i++) {
if (inner[i].innerHTML.includes(searchValue)) return i;
}
return 'no match'
}
// remember that indexing starts at 0,
// thus option 'Select Size' - is the first one with the index 0
// and `40` - is the index 1
getindex('40'); // returns index 1
函数getindex(searchValue){
//您可能希望为它们创建一个类或传递一个选项数组
//这是因为您的html在其他地方可能有选项
const inner=document.body.getElementsByTagName('option');
for(设i=0;i
function getindex(searchValue) {
// you probably want to have a class for them OR pass an array of options
// to this function, because your html might have options in other places
const inner = document.body.getElementsByTagName('option');
for (let i = 0; i < inner.length; i++) {
if (inner[i].innerHTML.includes(searchValue)) return i;
}
return 'no match'
}
// remember that indexing starts at 0,
// thus option 'Select Size' - is the first one with the index 0
// and `40` - is the index 1
getindex('40'); // returns index 1