$("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>
你不needjQuery 来完成这个简单的任务。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>"
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)