2010-07-23 77 views
4

我剛開始學習jQuery,並且熟悉jQuery如何使用選擇器來搜索特定的ID和類。但是,也可以在段落內標識純文本字符串嗎?我可以使用jQuery在HTML中定位一個文本字符串嗎?

例如,假設我想找到這些段落標記中的「汽油」,並把它轉換成一個鏈接:

<p>His veins burned gasoline. 
    It kept his motor running but it never kept him clean.</p> 

回答

4

你不會真的使用jQuery做替換。相反,只需使用javascript的.replace()方法即可。

(我給段落的ID來指定正確的段落。)

試試看:http://jsfiddle.net/yRCjN/1/

HTML

<p id='myparagraph'>His veins burned gasoline. 
    It kept his motor running but it never kept him clean.</p> 

的JavaScript/jQuery的

 // Cache the selected element so it only runs once. 
var $paragraph = $('#myparagraph'); 

    // Get the text and update it with the <a> tag 
var newcontent = $paragraph.text().replace(/(gasoline)/,'<a href="/some/link/path">$1</a>'); 

    // Set the new content 
$paragraph.html(newcontent); 

公園大道通向...

+0

非常感謝!這應該給我足夠的工作。並且也感謝你向JSfiddle提出了一些建議。 – 2010-07-23 21:44:02

1
var text = jQuery("#someId").text(); 
text = textreplace(/(gasoline)/, "<a href='http://some.url.here'>$1</a>"); 
jQuery("#someId").html(text); 
+0

無需在選擇了 「P」; 'jQuery('#someId')' – Matt 2010-07-23 20:59:32

+0

@Matt。真正。編輯! – 2010-07-23 21:00:24

1
$('p').text().replace('gasoline', '<a href="#">gasoline</a>'); 
相關問題