jquery - 使用jquery为每个设置id

标签 jquery

我看到了这个:

$("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/

相关文章:

jquery - 如何使用 JQuery 检查浏览器上安装/启用/禁用的 Flash 和 JavaScript

javascript - 如何将 id 添加到 .before 函数中的段落元素?

javascript - 悬停时的颜色没有改变

jquery - 如何让 jquery ui 标签工作?

php - 返回一个在 WordPress 简码中包含变量的字符串

jquery - 我的 header CSS 和 jQuery 有问题

jQuery 检查是否存在任何元素

jQuery 脚本引用

jquery foreach循环中的javascript函数不等待响应

javascript - 由于 header 导致 scrollto 偏移 javascript 的问题