我刚开始学习jQuery,并且熟悉jQuery如何使用选择器来搜索特定的ID和类。但是,也可以在段落内标识纯文本字符串吗?我可以使用jQuery在HTML中定位一个文本字符串吗?
例如,假设我想找到这些段落标记中的“汽油”,并把它转换成一个链接:
<p>His veins burned gasoline.
It kept his motor running but it never kept him clean.</p>
我刚开始学习jQuery,并且熟悉jQuery如何使用选择器来搜索特定的ID和类。但是,也可以在段落内标识纯文本字符串吗?我可以使用jQuery在HTML中定位一个文本字符串吗?
例如,假设我想找到这些段落标记中的“汽油”,并把它转换成一个链接:
<p>His veins burned gasoline.
It kept his motor running but it never kept him clean.</p>
你不会真的使用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);
.text()
.replace()
与包裹在一个<a>
元素相同的文字取代“汽油”的段落的内容使用jQuery的.html()
方法来更新与新的段落内容。
公园大道通向...
var text = jQuery("#someId").text();
text = textreplace(/(gasoline)/, "<a href='http://some.url.here'>$1</a>");
jQuery("#someId").html(text);
无需在选择了 “P”; 'jQuery('#someId')' – Matt 2010-07-23 20:59:32
@Matt。真正。编辑! – 2010-07-23 21:00:24
$('p').text().replace('gasoline', '<a href="#">gasoline</a>');
非常感谢!这应该给我足够的工作。并且也感谢你向JSfiddle提出了一些建议。 – 2010-07-23 21:44:02