2013-12-15 22 views
0

我是Jquery的新手,可能會引起混淆。但非常感謝你檢查這個。我想修改元素中的文本。例如:Jquery如何更改TEXT_NODE

<div class="testit">test it for no.1 and test.com <img=...> <a href="http://test.com/">test it</a></div> 
<div class="testit">another test for No.2 and test2.com and test.com <img=...> <a href="http://test2.com/">test2</a> Another description</div> 

我想使用jQuery修改每個類「調用testIt」元素的「一些文本conents」的一部分,但我也想保持其他標記元素不變。例如:期望的輸出將是:

<div class="testit">test it for no.1 and <a href="http://test.com">test.com</a> <img=...> <a href="http://test.com">test it</a></div> 
<div class="testit">another test for No.2 and <a href="http://test2.com">test2.com</a> and <a href="http://test.com">test.com</a> <img=...> <a href="http://test2.com/">test2</a> Another description</div> 

以下JQuery可以獲取原始內容但無法修改它們。你能告訴我如何改變jQuery程序嗎?

var getTextNodesIn = function(el) { 
    return jQuery(el).find().andSelf().contents().filter(function() { 
    return this.nodeType == Node.TEXT_NODE; 
    });}; 
var current_text=getTextNodesIn(this); 
current_text.text('new contents here'); 
+0

變化'的jQuery(EL).find()。andSelf()''到的jQuery(EL)'。不帶參數調用'.find'會返回一個空的jQuery對象。 –

+0

並且您正在返回文本節點,以便設置其節點值...例如:'current_text [0] .nodeValue'如果您有許多節點循環並設置它。 http://jsfiddle.net/DJ8j6/ – PSL

+0

對不起,我不清楚,我更新了一些細節的帖子。 – user3103660

回答

0

增加了一個正則表達式來檢測,如果字符串中包含的值

var count = 1; 
$('.testit').each(function() { 
//check if the test string is found 
var str = $(this).text(); 
var patt = new RegExp("test.com"); 
var res = patt.test(str); 
if(res){ 
    $(this).text("new text contents No." + count); 
    count++; 
} 
}); 
+0

感謝馬克的快速回答。由於我之前的版本太簡單,並且確實反映了我需要的所有內容,所以我再次更新了我的帖子我想將一些關鍵字替換爲超鏈接,而現有的超鏈接,img和媒體鏈接不會受到影響。我嘗試的功能實際上在.each()中。我不確定我是否足夠清楚。謝謝。 Jay – user3103660

+0

@ user3103660我不明白,也不會在您的帖子中看到更改。 – Mark

+0

如果它是一個純粹的test.com文本,那麼它需要變成test.com。如果它已經是格式,那麼不要更改。 – user3103660