gpt4 book ai didi

jquery - 我可以使用 jQuery 来定位 HTML 中的文本字符串吗?

转载 作者:行者123 更新时间:2023-12-01 00:08:58 25 4
gpt4 key购买 nike

我刚刚开始学习 jQuery,并且逐渐熟悉 jQuery 如何允许我使用选择器来搜索特定的 ID 和类。但是是否也可以识别段落内的纯旧文本字符串?

例如,假设我想在这些段落标签中查找“汽油”并将其转换为链接:

<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 );
  • 您可以使用 jQuery 的 .text() 获取该段落的内容
  • 执行.replace()在文本内容上将“汽油”替换为 <a> 中包含的相同文本元素
  • 使用 jQuery 的 .html()方法用新内容更新段落。

  • http://api.jquery.com/text/

  • http://api.jquery.com/html/

公园大道通向...

关于jquery - 我可以使用 jQuery 来定位 HTML 中的文本字符串吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3322267/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com