我有这样的 HTML 结构:
<tr>
<td class="CT">
anything –
<span class="cu">
<a href="#"></a>
</span> –
<span class="dt">content</span>
</td>
</tr>
现在我只想选择anything
来自所有 HTML 代码。如何?我只能选择它的文本:
$('tr').text();
/* but the way, there is two function that I feel they can be useful:
1. closest()
2. siblings() */
请问有什么解决办法吗?
注意:我无法使用replace()
,因为有时<span>
有不同的内容或 <a>
的 href .
编辑: anything
不仅仅是一个字符串。它可以是以下之一:
anything
=this is a <a href="www.example.com">test</a>
anything
=hello, how are you
anything
=<a href="www.example.com">test1</a> and <a href="www.example.com">test2</a>
其实我想要td.CT
的所有内容后面<span class="cu">
。实际上,它是评论的内容(用于编辑它),我想将其设置在文本区域中(同样,用于编辑它)。
最佳答案
这是一种在 <span class="cu">
之前提取“任何内容”的(hacky)方法。节点。
- 查找 td 的所有内容
- 从 jQuery 集合转换为 js 数组
- 减少数组,使所有节点达到但不包括
<span class="cu">
被插入数组。 - 将节点数组包裹在
$()
中形成一个 jQuery 集合。 - 最后将集合附加到某个 DOM 容器以使结果可见。
var $myFragment = $($(".CT").contents().get().reduce(function(obj, node) {
if($(this).is("span.cu")) {
obj.stop = true;
}
if(!obj.stop) {
obj.nodes.push(node);
}
return obj;
}, {nodes:[], stop:false}).nodes);
// then
$("#myResult").append($myFragment);
// or maybe
//$("#myResult").append($myFragment.text());
我确信有一种更简单的方法,但我现在想不出。
演示:
- 示例 1:http://jsfiddle.net/1xonqeob/1/
- 示例 2:http://jsfiddle.net/1xonqeob/2/
- 示例 3:http://jsfiddle.net/1xonqeob/3/
这就是我所说的更简单的方法:
var $myFragment = $(".CT").contents().filter(function(i, node) {
return !$(node).prevAll().addBack().filter("span.cu").length;
});
演示:http://jsfiddle.net/1xonqeob/4/
这是更通用的东西;一个 jQuery 插件 .prevAllNodes()
,其中:
- 对要在其之前查找节点的元素进行操作。
- 接受要查找的节点类型或节点类型数组。不传递任何内容或
[]
查找所有节点类型。 - 返回节点的 jQuery 集合。
// *****************************************************
// A jQuery plugin to find DOM nodes of specified types
// before the first element in a jQuery collection.
// *****************************************************
$.fn.prevAllNodes = function(types) {
types = types || [];
if(!$.isArray(types)) types = [types];
var that = this.eq(0);
var nodes = that.parent().contents().get().reduce(function(nodes, node) {
nodes.stop = nodes.stop || (node == that.get(0));
return nodes.stop ? nodes : nodes.concat(node);
}, []).filter(function(node) {
return types.length == 0 || $.inArray(node.nodeType, types) > -1;
});
return $(nodes);
}
使用如下:
var $commentsNodes = $(".CT span.cu").prevAllNodes([Node.COMMENT_NODE]);
// $commentsNodes is a jQuery collection
// To read comments' text, you need to know to use the `.nodeValue` property. jQuery's $(commentNode).text() will not work.
演示:http://jsfiddle.net/1xonqeob/5/
$.fn.nextAllNodes() 非常相似
关于javascript - 如何选择特定元素后面的元素的所有内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34112298/