如何獲取沒有子元素的元素的文本? element.textContent
也沒有element.innerText
似乎工作。在javascript中獲取無子元素的文本
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
並不能真正幫助這裏的原因: Imaginge以下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
本身(「上次訪問......」)
PLZ發表您的HTML – Jigs 2012-03-31 12:47:02
任何代碼?您的選擇器可能是錯誤的,'.textContent'和'innerText'爲空時'element'不包含任何內容。 – 2012-03-31 12:47:29
你的意思是什麼,「沒有孩子」? – Pointy 2012-03-31 13:07:53