【发布时间】:2012-04-14 21:42:58
【问题描述】:
如何获取没有子元素的元素的文本?
element.textContent 和 element.innerText 似乎都不起作用。
HTML:
<body>
<h1>Test Heading</h1>
<div>
Awesome video and music. Thumbs way up. Love it. Happy weekend to you and your family. Love, Sasha
</div>
</body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript">
fool("body");
</script>
这是fool 函数:
jQuery.fn.justtext = function(text) {
return $(this).clone()
.children()
.remove()
.end()
.text();
};
function fool(el) {
reverse(el);
function reverse(el) {
$(el).children().each(function() {
if($(this).children().length > 0) {
reverse(this);
if($(this).justtext() != "")
reverseText(this);
} else {
reverseText(this)
}
});
}
function reverseText(el){
var text = el.textContent;
var frag = text.toString().split(/ /);
var foo = "";
var punctation_marks = [".",",","?","!"," ",":",";"];
for(i in frag){
if(punctation_marks.indexOf(frag[i]) == -1)
foo += actualReverse(frag[i],punctation_marks) + " ";
}
el.textContent = foo;
}
function actualReverse(text,punctation_marks) {
return (punctation_marks.indexOf(text.split("")[text.split("").length-1]) != -1)?text.split("").slice(0,text.split("").length-1).reverse().join("") + text.split("")[text.split("").length-1] : text.split("").reverse().join("");
}
}
编辑:使用node.nodeType 并没有真正的帮助,原因如下:
对以下 HTML 进行成像
<td class="gensmall">
Last visit was: Sat Mar 31, 2012 10:50 am
<br>
<a href="./search.php?search_id=unanswered">View unanswered posts</a> | <a href="./search.php?search_id=active_topics">View active topics</a>
</td>
如果我使用nodeType,则只有a 元素的文本会改变,td 本身不会改变(“上次访问...”)
【问题讨论】:
-
任何代码?您的选择器可能是错误的,
.textContent和innerText为空时,element不包含任何内容。 -
“没有孩子”到底是什么意思?
-
@Pointy 我只想要(与最后一个示例相关 - td 单元格)“最后一次访问是:2012 年 3 月 31 日星期六上午 10:50”,没有来自锚的文本跨度>
-
那么您想要一个节点及其所有后代节点的文本内容吗?看到“没有孩子”的部分让我觉得你想跳过后代。
-
不,我不想要文本 + 后代,而只想要文本
标签: javascript jquery text children