我正在尝试制作一个简单的 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/