javascript - jQuery 替换 HTML 标签插件

标签 javascript jquery

我正在尝试制作一个简单的 jQuery 插件来就地替换元素的标签。这是来源:

$.fn.replaceTag = function(tag, copyAttributes = true) {
  return this.each(function() {
    const newTag = tag || this.dataset.tag;

    if (!newTag.length) {
        return true;
    }

    const replacement = document.createElement(tag);

    if (copyAttributes) {
        for (let attr of this.attributes) {
            replacement.setAttribute(attr.nodeName, attr.nodeValue);
        }
    }

    replacement.innerHTML = this.innerHTML;

    this.replaceWith(replacement);
  });
};

下面是它的实现示例:

const $xyz = $('.xyz');
setTimeout(() => $xyz.replaceTag('h1'), 2000);
setTimeout(() => $xyz.replaceTag(), 3000); /// Switch to tag defined by data-tag attribute
setTimeout(() => $xyz.replaceTag('h6', false), 5000); /// Drop attributes

这是一个演示:https://jsfiddle.net/jasongardner/cpy6e51h/

问题是:

假设我们的元素是<p class="xyz" data-tag="b">Hi!</p> .我希望这个例子能改变初始的 <p>标记为 <h1> , 然后到 <b> , 最后到 <h6> (没有任何 HTML 属性)。

但事实并非如此。第一次替换标签,但在后续调用中不会再次替换。

我错过了什么?!

你能推荐任何已经存在的这样的插件吗?

谢谢!

最佳答案

这是因为 $xyz 在第一次替换后引用了一个不存在的对象 - 来自文档(http://api.jquery.com/replacewith/):

The .replaceWith() method, like most jQuery methods, returns the jQuery object so that other methods can be chained onto it. However, it must be noted that the original jQuery object is returned. This object refers to the element that has been removed from the DOM, not the new element that has replaced it.

如果你在每次调用之前重新初始化 $xyz,它就可以工作

关于javascript - jQuery 替换 HTML 标签插件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50143059/

相关文章:

javascript - 对于 Greasemonkey 中的这个 jQuery 示例,为什么会触发 alert() 但不会触发 console.log()?

javascript - Strope.js 客户端连接到服务器,断开连接/超时

javascript - 使用 javascript 通过 select 显示表格

ajax - MVC 4、Jquery Mobile、Ajax.BeginForm 导致表单提交两次

javascript - Jquery UI 自动完成的限制结果

javascript - 动态访问复杂的Javascript对象

javascript - 没有中间表达式重复的正则表达式 (axb|cxd)

javascript - jQuery 的隐式循环变为 "both ways"?

javascript - innerWidth 在手机上没有得到正确的宽度

javascript - 为什么我的 javascript/jquery 没有按顺序执行?