我正在做这样的事情来从子节点检索文本内容 一个班级:
$(data).find(".mw-content-ltr").contents().each(function(_, row) {
// ...
} else if ( row.nodeType === 3 && $.trim(row.nodeValue).length ) {
var textNodeValue = $.trim(row.nodeValue);
console.log(textNodeValue);
}
});
问题是,如果文本节点内部有一些锚点,如下所示:
When<a href="/wiki/Raquel_Ochmonek" title="Raquel Ochmonek"> Raquel Ochmonek</a> comes over to sit
for <a href="/wiki/Brian_Tanner" title="Brian Tanner">Brian</a>,
a burglar breaks into the house through the master bedroom
where <a href="/wiki/ALF" title="ALF">ALF</a> is hiding.
我的代码不会检索它们,导致类似这样的内容:
When
comes over to sit for
, a burglar breaks into the house through the master bedroom where
is hiding.
当我需要这样的东西时:
When Raquel Ochmonek comes over to sit for Brian, a burglar breaks into the house through the master bedroom where is hiding.
提前致谢!
答案 0 :(得分:3)
试试这个:
$(".mw-content-ltr").text()
比较两者:http://jsfiddle.net/KyleMuir/GeRVV/2/
编辑:由于课程中还有其他您不感兴趣的数据,这样的工作会不会有效?
$(".mw-content-ltr").contents().each(function (_, row) {
if (row.nodeType === 3 && $.trim(row.nodeValue).length) {
var textNodeValue = $.trim(row.nodeValue);
console.log(textNodeValue);
} else if (row.nodeType == 1) {
var nodeValue = $.trim($(row).text());
console.log(nodeValue);
}
});