2010-07-23 75 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>'); 
相关问题