對於HTML
<b id="test">我是 b 的文字<i>我是 i 的文字</i></b>
我只想得到 "我是 b 的文字" 這幾個字 要怎做呢?
我目前是用 jQuery
$copy = $("#test").clone(); //先 copy 節點
$copy.children().remove("*"); //移除所有子節點
var text = $copy.text(); //再去取得文字
alert(text);
可以解決問題 但用這種方式會複製整個節點~~ 應該效率會很差...有解嗎
$copy[0].firstChild.nodeValue 可以取得「我是 b 的文字」,不過不知道你的需求是不是就這麼單純而已
小弟分享一個簡單的方式。假如test元素的結構正如版主說的那麼簡單的話,可以改用string.substr()函式就行了,例如:
<pre class="c" name="code">
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<script src="jquery.js"></script>
<script type="text/javascript">
$(function(){
var childHtml=$('#test').html(); //取得#test的html源文字
var len=childHtml.indexOf('<'); //找到第一個<字符的位置
var result=childHtml.substr(0,len); //用substr取得所需的字串
alert(result);
});
</script>
<b id="test">我是 b 的文字<i>我是 i 的文字</i></b>
希望有幫助~!
P.S:本來想用RegEXP來取得所需字串,不過那也是會造成效率上的問題,所以先不用...