循环遍历 document.evaluate() 中使用的字符串会返回意外结果

问题描述 投票:0回答:1

我正在尝试重新格式化网页,以便某些单元格(td)根据其值突出显示。 我有几个正在寻找的标签,并且想尝试循环执行此操作。

console.log 中的“标签”似乎是正确的,但

matchingElement
未设置为正确的元素。 但是,如果我将
label
替换为
"Animal:"
,例如在
document.evaluate()
行中,它就可以工作。 当它搜索由变量表示的标签时,它似乎不起作用。 (没有错误,但它返回一个不包含我正在搜索的文本的匹配元素。我无法判断它正在搜索什么或为什么匹配。)

const labels = ["Animal:", "Human:"];

labels.forEach((label) => {
  console.log("Label: " + label);
  matchingElement = document.evaluate('//td[contains(text(), label)]/following-sibling::td', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
  code = matchingElement.innerHTML;
  console.log("Code: " + code);
  if ( code == 10 || code == 30 ) {
    matchingElement.innerHTML = '<span style="color:green; font-weight:bold;">' + code + '</span>';
    console.log("Color green");
  } else {
    matchingElement.innerHTML = '<span style="color:red; font-weight:bold;">' + code + '</span>';
    console.log("Color red");
  }
});
javascript tampermonkey userscripts
1个回答
0
投票

根据@Barmer的建议回答:

const labels = ["Animal:", "Human:"];

labels.forEach((label) => {
  console.log("Label: " + label);
  matchingElement = document.evaluate('//td[contains(text(), "' + label +'")]/following-sibling::td', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
  code = matchingElement.innerHTML;
  console.log("Code: " + code);
  if ( code == 10 || code == 30 ) {
    matchingElement.innerHTML = '<span style="color:green; font-weight:bold;">' + code + '</span>';
    console.log("Color green");
  } else {
    matchingElement.innerHTML = '<span style="color:red; font-weight:bold;">' + code + '</span>';
    console.log("Color red");
  }
});


© www.soinside.com 2019 - 2024. All rights reserved.