我有这样的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>
或href的内容不同<a>
。
编辑: 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">
节点之前提取“任何内容”的(简单的)方法。
<span class="cu">
都推入阵列。$()
成一个jQuery集合。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());
我敢肯定有一种更简单的方法,但是我现在想不起来。
DEMOS:
这就是我所说的更简单的方法:
var $myFragment = $(".CT").contents().filter(function(i, node) {
return !$(node).prevAll().addBack().filter("span.cu").length;
});
演示:http : //jsfiddle.net/1xonqeob/4/
还有一些更通用的东西;jQuery插件.prevAllNodes()
,它:
[]
查找所有nodeType。// *****************************************************
// 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()会非常相似
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句