我看到了这个:
$("div").children().andSelf().contents().each(function(){
if (this.nodeType == 3) {
var $this = $(this);
$this.replaceWith($this.text().replace(/(\w)/g, "<span>$&</span>"));
}
});
这里: wrap each char in except tags with jQuery
现在我尝试给每个跨度一个 id,但它们最终都具有相同的 id。 然而,记录到控制台的索引是不同的。
$("#content").children().andSelf().contents().each(function(index){
console.log(index);
if (this.nodeType == 3) {
var $this = $(this);
$this.replaceWith($this.text().replace(/(\w)/g, "<span id="+index+">$&</span>"));
}
});
最佳答案
这个answer可能对你有用。
如果您想要一个范围内的每个字母,每个字母都有一个唯一的 ID,则可以这样做:
$("#content").children().andSelf().contents().each(function(index){
if (this.nodeType == 3) {
var $this = $(this);
$this.replaceWith($this.text().replace(/\w/g, function(text,index2) {
return "<span id="+index+""+index2+">" + text + "</span>";
}));
}
});
观察:我不确定每个浏览器都支持这种形式的Regex.replace
。使用 FF3.6 和 Chrome 进行测试。
澄清一下:这个表格对我来说也是新的,今天刚学到,但在网上找不到相关文档。看来,对于不带捕获组的正则表达式,第一个参数是匹配的文本,第二个参数是原始字符串中的索引。否则,第二个参数将成为第一个捕获的组,并且我假设第三个参数是第二个 c.g。等等...如果有人知道在哪里可以找到更多信息,我也对此感兴趣。
关于jquery - 使用jquery为每个设置id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8781391/