我想找到页面上的所有 h2 标签,然后将前两个词包装在 span 标签中。我检查了this stackoverflow question ,但这对我没有帮助。
我可以按照这个链接和 dd 跨度到前 2 个单词,但唯一的问题是如果我在 h2 标签内有 html 例如我在 h2 标签内有超链接。
任何人都可以帮助我如何制作这段代码,以便忽略 html 并且只考虑前两个词吗?
非常感谢任何帮助!
我的 fiddle :
我的JS:
jQuery(document).ready(function($){
jQuery('h2').html(function (i, html) {
return html.replace(/(\w+\s\w+)/, '<span>$1</span>')
});
});
我的 HTML :
<h2>
<a title="test post 2" href="#">
test text dolor sit enum
</a>
</h2>
<h2>lorem ipsum dolor sit enum</h2>
最佳答案
这应该适合您。
jQuery(document).ready(function($){
jQuery('h2').html(function (i, html) {
if(/<[a-z][\s\S]*>/i.test(html)) {
html = jQuery.parseHTML(html);
return html[0].innerHTML.replace(/(\w+\s\w+)/, '<span>$1</span>');
}
return html.replace(/(\w+\s\w+)/, '<span>$1</span>');
});
});
h2 {
color:#f2f2f2;
}
h2 span {
color:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2><a title="test post 2" href="#">test text dolor sit enum</a></h2>
<h2>lorem ipsum dolor sit enum</h2>
关于javascript - 选择 h2 标签的前两个词并包裹在 span 标签中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35464411/