嗨,我正在尝试使用cheerio从网站上获取列表的索引号。例如“ 40-仅剩一个”的索引号是2。
我将如何通过仅匹配“ 40”(只剩下一个)来获得数字2?
<option value="">Select Size</option>
<option value="2970"> 40 - only one left</option>
<option value="2973"> 41 - only one left</option>
<option value="2976"> 42 - only one left</option>
答案 0 :(得分:1)
您可以首先使用cheerio / jQuery选择器<option>
通过文本选择:contains
(文本可以是任何东西),然后调用函数index
以使其索引进入其父级:
var index = $("option:contains('40')").index();
注意:函数index
返回一个从0开始的0索引结果,如果要1索引结果,只需将其加1。
演示(使用基于cheerio的jQuery)
var index = $("option:contains('40')").index();
console.log(index);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
<option value="">Select Size</option>
<option value="2970"> 40 - only one left</option>
<option value="2973"> 41 - only one left</option>
<option value="2976"> 42 - only one left</option>
</select>
答案 1 :(得分:0)
您可以尝试以下操作:
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