从jQuery中的html字符串中删除元素 [英] Remove element from html string in JQuery
问题描述
因此,我很困惑如何从JQuery中排除子孩子...
So, I am pretty stumped as to how to exclude a sub children from getting selected in JQuery...
这是我的字符串中的HTML结构:
Here is my HTML structure in my string:
<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提要的结构中解析文本我想在这里提取的文本".
Note: I didn't choose this. I am trying to parse the text "Text I want to extract here" out of this structure that comes from some arbitrary xml feed.
这是我的测试JQuery:(d是HTML字符串)
Here is my test JQuery: (d is the HTML string)
$('tr > td:eq(1) > table', d).remove();
var c = $('tr > td:eq(1)', d).text();
第一行不会删除表格.我测试了选择器,它确实设法选择了元素.我使用错误的方法删除了元素吗?
The first line does not remove the table. I test the selector and it does manage to select the element. Am I using the wrong method to remove the element?
我也尝试过使用not()
和replaceWith()
时没有运气.
I had also tried using not()
and replaceWith()
with no luck.
$('tr > td:eq(1)', d).not('tr > td:eq(1) > table').text();
和
$('tr > td:eq(1) > table', d).replaceWith("");
我对其他选择方法持开放态度,这些选择方法将仅检索特定td内的文本.
I am open to other selection methods that will retrieve only the text within that specific td.
推荐答案
您声明"d
是HTML字符串" .
You state that "d
is the HTML string".
这意味着当您执行此操作时:
This means that when you do this:
$('tr > td:eq(1) > table', d).remove();
var c = $('tr > td:eq(1)', d).text();
...您正在使用相同的 未修改 字符串创建元素两次.
...you're creating elements from the same unmodified string twice.
您需要从其中创建元素 ,然后缓存这些元素.
You need to create elements out of it once, then cache those elements.
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()
方法,您可以像这样一口气完成所有操作:
Or, because of jQuery's .end()
method, you could do it all in one shot like this:
var c = $(d).find('tr > td:eq(1)')
.children('table')
.remove()
.end()
.text();
JSFIDDLE DEMO
这篇关于从jQuery中的html字符串中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!