gpt4 book ai didi

jquery , append html

转载 作者:行者123 更新时间:2023-12-01 07:35:28 26 4
gpt4 key购买 nike

我有这种 HTML :

<h1> Text1 Text2 </h1>

我想通过 jquery 更改此 HTML:

<h1> <span>Text1</span> Text2 </h1>

我的头脑只是 append 和正则表达式(也许你有其他想法),不幸的是我没有“正则表达式”的经验。 “Text1”是可变的..它应该是“h1”中的第一个文本有人可以帮助我吗!

谢谢!

最佳答案

假设您想将每个 H2 的第一个单词包裹在一个 span 中,并且保证 H2 内部没有 HTML 标签,您可以按如下方式执行:

// For each H2.
$('h2').each(function() {
// Get text.
var text = $(this).text();
// Split into words.
var words = text.split(' ');
// Wrap the first word.
if (words.length > 0) words[0] = '<span>' + words[0] + '</span>';
// Join the results into a single string.
var result = words.join(' ');
// Put the results back into the H2.
$(this).html(result);
});

或者使用正则表达式:

// For each H2.
$('h2').each(function() {
$(this).html($(this).text().replace(/^(\W*)\b(\w+)\b/, '$1<span>$2</span>'));
});

关于jquery , append html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2308032/

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