$("div.date")
.contents()
.filter(
function(){
return this.nodeType != 1;
})
.wrap("<span/>");
我是新手,我认为代码可以解决问题,但它将所有内容都包装在 <span>
中像这样:
<div class='date'><span>
2011 年 12 月 22 日 </span></div>
它应该是这样的:
<div class='date'>
<span>Dec</span>
<span>22,</span>
<span>2011</span>
</div>
最佳答案
您不需要 jQuery 来完成这个简单的任务。 String.prototype.replace
和正则表达式应该可以解决问题。
我只是制作了一些简单的实用函数,用于包装字母、单词和行:
/**
* Wraps a string around each character/letter
*
* @param {string} str The string to transform
* @param {string} tmpl Template that gets interpolated
* @returns {string} The given input as splitted by chars/letters
*/
function wrapChars(str, tmpl) {
return str.replace(/\w/g, tmpl || "<span>$&</span>");
}
/**
* Wraps a string around each word
*
* @param {string} str The string to transform
* @param {string} tmpl Template that gets interpolated
* @returns {string} The given input splitted by words
*/
function wrapWords(str, tmpl) {
return str.replace(/\w+/g, tmpl || "<span>$&</span>");
}
/**
* Wraps a string around each line
*
* @param {string} str The string to transform
* @param {string} tmpl Template that gets interpolated
* @returns {string} The given input splitted by lines
*/
function wrapLines(str, tmpl) {
return str.replace(/.+$/gm, tmpl || "<span>$&</span>");
}
用法非常简单。只需传入要包装的字符串作为第一个参数。如果您需要自定义标记,请将其作为第二个参数传入,而 $&
将替换为每个字符/单词/行。
var str = "Foo isn't equal\nto bar.";
wrapChars(str); // => "<span>F</span><span>o</span><span>o</span> <span>i</span><span>s</span><span>n</span>'<span>t</span> <span>e</span><span>q</span><span>u</span><span>a</span><span>l</span> <span>t</span><span>o</span> <span>b</span><span>a</span><span>r</span>."
wrapWords(str); // => "<span>Foo</span> <span>isn</span>'<span>t</span> <span>equal</span> <span>to</span> <span>bar</span>."
wrapLines(str); // => "<span>Foo isn't equal</span> <span>to bar.</span>"
关于javascript - 如何将元素的每个单词包装在 span 标签中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8609170/