根据标签包含的文本将 id 添加到标签
我需要根据 h2 包含的文本添加一个“id”。我所拥有的不起作用。
像这样开始
<h2>Revision 3</h2>
脚本
$('h2:contains(" Revision 3 ")').replaceWith( "<h2 id="rev3">Revision 3</h2>");
像这样运行 结束
<h2 id="rev3">Revision 3</h2>
I need to add an "id" to the h2 based on the text it contains. What I have is not working.
Starts like this
<h2>Revision 3</h2>
Scripts runs
$('h2:contains(" Revision 3 ")').replaceWith( "<h2 id="rev3">Revision 3</h2>");
Ends like this
<h2 id="rev3">Revision 3</h2>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
循环遍历所有 h2 标签,如果标签文本为
Revision 3
,则将 id 设置为rev3
Loops through all h2 tags, if the tag text is
Revision 3
it set the id torev3
或者,如果您只是想向其中添加 ID,您可以使用更快的方法,例如:
Or if you just want to add ID to it you might use something faster like:
您不能使用字符串分隔符在字符串中引用字符串...因此您不能在用
" 分隔的字符串内使用
"
>,但是您可以在用"
分隔的字符串内使用'
。例如:应该可以。此外,开头的空格,字符串的 和 end 应该被删除,因为它们不在您要查找的字符串中:
最后,使用类似以下内容不是更容易:
鉴于
id
<必须在文档中是唯一的,也许也值得将选择器限制为仅一个元素:You can't quote a string within a string using the string delimiters...so you can't use
"
inside a string delimited with"
, but you could use'
inside a string delimited with"
). For example:Should work. Also, the spaces at the beginning, and end, of the string should be removed, since they're not in the string you're looking for:
And, finally, would it not be easier to use something like:
Given that an
id
must be unique within a document it's maybe also worth limiting the selector to only one element:我认为修订版 3 开头和结尾的提取空格造成了一个问题。
试试这个:
I think the extract spaces at the begin and end of Revision 3 are creating an issue.
Try this: