[英]javascript function return different result than expected
In this website在这个网站
https://www.worldometers.info/coronavirus/ https://www.worldometers.info/coronavirus/
I use this javascript function to know the position of the country in the table我用这个javascript function 知道表中国家的position
{
function findMatchingRow(word) {
const found = []
const trList = document.querySelectorAll('#main_table_countries_today > tbody > tr')
trList.forEach((tr, i) => {
if (tr.textContent.match(word)) {
found.push({
index: i,
content: tr.textContent
})
}
});
return found
}
const matches = findMatchingRow("Australia")
console.log(matches)
if (matches.length > 0) {
console.log('found at:', matches.map(m => m.index))
}
}
For only Australia, it returns 8 instead of 35仅对于澳大利亚,它返回 8 而不是 35
for other countries like poland it gives correct number,对于像波兰这样的其他国家,它给出了正确的数字,
I still can't figure it out我还是想不通
Any help will be appreciated !任何帮助将不胜感激 !
You do not have to get text content from the entire row, You can just match first td
content.您不必从整行中获取文本内容,您只需匹配第一个
td
内容即可。 There are places like Australia in anywhere in tr
. tr
的任何地方都有像澳大利亚这样的地方。 So narrow down the search.所以缩小搜索范围。
function findMatchingRow(word) {
const trList = [...document.querySelectorAll(
"#main_table_countries_today > tbody > tr"
)];
let found;
trList.some((tr, i) => {
const name = tr.children[0].textContent.trim();
if (name.includes(word)) {
found = {
index: i,
content: tr.textContent,
};
}
return found;
});
return found;
}
const found = findMatchingRow("Australia");
if (found) {
console.log("found at:"+ JSON.stringify(found));
console.log("found at:"+ found.index);
}
you only search in text-Content of the whole tr (row).您只搜索整个 tr (行)的文本内容。 text-Content are all nodes.
text-Content 都是节点。 Australia results in an Array, cause many entries have "Australia/Oceania" as data-continent attr.
澳大利亚导致一个数组,因为许多条目将“澳大利亚/大洋洲”作为数据大陆属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.