我正在尝试找到一个函数,可以将字符串中的第一个单词包装在span标签中。
但不幸的是没有成功。
有人能帮我吗?
非常感谢
Dom
jQuery
中实现此功能。我认为你需要使用正则表达式来确切地 添加 span。jQuery
从 DOM 中获取文本,并在使用正则表达式将 span
添加到字符串后,在 DOM 中进行更新。<div id="container">This is the text</div>
<script type="text/javascript">
jQuery(function($){
// get the text you want to transform in a variable
var html = $('#container').html();
// doing the transformation (adding the span) with a regular expression
html = html.replace(/^([^\s]*)(.*)/, "<span class=\"first-word\">$1</span>$2");
// update your text
$('#container').html(html);
// or in one line:
$('#container').html( ('#container').html().replace(/^([^\s]*)(.*)/, "<span class=\"first-word\">$1</span>$2") );
});
</script>
这是您将获得的内容:
<div id="container"><span class="first-word">This</span> is the text</div>
(function () {
var node = $("div").contents().filter(function () { return this.nodeType == 3 }).first(),
text = node.text(),
first = text.slice(0, text.indexOf(" "));
if (!node.length)
return;
node[0].nodeValue = text.slice(first.length);
node.before('<span>' + first + '</span><br/>');
})();
var first;
var i=0;
$("p").each(function() {
first = $("p")[i].innerHTML;
$("p")[i].innerHTML = "<span class='first'>" + first.slice(0, first.indexOf(' ')) + "</span>" + first.slice(first.indexOf(' '));
i++;
});
.each()
方法迭代以便操作多个节点。 - jensgram