所以,我对如何在 JQuery 中排除子子项被选中感到非常困惑......
这是我的字符串中的 HTML 结构:
<table>
<tr>
<td>some data I don't want.</td>
<td>
<table><tr><td>more data I don't want</td></tr></table>
Text I want to extract here.
</td>
</tr>
</table>
注意:我没有选择这个。我正在尝试从来自任意 xml feed 的结构中解析文本“我想在此处提取的文本”。
这是我的测试 JQuery:(d 是 HTML 字符串)
$('tr > td:eq(1) > table', d).remove();
var c = $('tr > td:eq(1)', d).text();
第一行不删除表格。我测试了选择器,它确实成功选择了该元素。我是否使用了错误的方法来删除元素?
我也尝试过使用 not()
和 replaceWith()
但没有成功。
$('tr > td:eq(1)', d).not('tr > td:eq(1) > table').text();
和
$('tr > td:eq(1) > table', d).replaceWith("");
我愿意接受其他选择方法,这些方法将仅检索该特定 td 中的文本。
最佳答案
您声明“d
是 HTML 字符串”。
这意味着当您执行此操作时:
$('tr > td:eq(1) > table', d).remove();
var c = $('tr > td:eq(1)', d).text();
...您正在从同一个未修改字符串创建元素两次。
<小时/>您需要从中创建元素一次,然后缓存这些元素。
var $d = $(d); // create the elements out of the string, and cache the set
$d.find('tr > td:eq(1) > table').remove(); // remove table from the cached set
var c = $d.find('tr > td:eq(1)').text(); // target the <td> and get its text
<强> JSFIDDLE DEMO
<小时/>或者,由于 jQuery 的 .end()
方法,您可以像这样一次性完成所有操作:
var c = $(d).find('tr > td:eq(1)')
.children('table')
.remove()
.end()
.text();
<强> JSFIDDLE DEMO
关于jquery - 从 JQuery 中的 html 字符串中删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8359828/