包裹跨度中的每个字符
我试图在一个范围内包装每个数字。
这是我在的地方。
12345 12345 12345 $('.numbers').each(function (index) { var characters = $(this).text().split(""); $(this).empty(); $.each(characters, function (i, el) { $(this).append("" + el + "</span"); }); });
我的语法在哪里出错?
this
$.each
中的this
在$('.numbers').each
是不一样的$('.numbers').each
你都必须将它保存到变量才能在那里使用它。
$this = $(this); $this.empty(); $.each(characters, function (i, el) { $this.append("" + el + "
你可以使用简单的正则表达式
$('.numbers').html(function (i, html) { return html.replace(/(\d)/g, '$1'); });
演示: 小提琴
要么
$('.numbers').html(function (i, html) { var chars = $.trim(html).split(""); return '' + chars.join('') + ''; });
演示: 小提琴
this
就是你现在所认为的
$(this).append("" + el + "
添加控制台行会显示this
是什么
console.log(this); //String {0: "1", length: 1}
您需要从外部范围获取此信息,将其存储在变量中并引用它。
var elem = $(this); var characters = elem.text().split(""); elem.empty(); $.each(characters, function (i, el) { elem.append("" + el + "