使用 jquery 替换元素名称,同时保留属性

发布于 2024-09-02 21:06:29 字数 517 浏览 5 评论 0 原文

我正在尝试创建一个 jquery 设置,其中 的所有实例都更改为 。这很容易做到:

$("i").each(function(){
    $(this).replaceWith($('<em>' + this.innerHTML + '</em>'));
});

但我无法弄清楚如何更改所有 标签但保留每个标签的单独属性。所以如果我有 Example Text 我希望将其更改为 示例文本

感谢您的帮助!

I'm trying to create a jquery setup where all instances of <i> are changed to <em>. It's easy enough to do with:

$("i").each(function(){
    $(this).replaceWith($('<em>' + this.innerHTML + '</em>'));
});

But what I am having trouble figuring out is how to change all the <i> tags but retain each ones individual attributes. So if I have <i style="background-color: #333;" alt="Example" title="Example">Example Text</i> I would like it to change to <em style="background-color: #333;" alt="Example" title="Example">Example Text</em>

Thanks for any help!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

许你一世情深 2024-09-09 21:06:29

国际海事组织的错误方法。

我建议直接在 DOM 中替换实际元素本身。也许这个问题有帮助:

jQuery 将 DOM 元素转换为不同类型

Wrong approach IMO.

I'd recommend replacing the actual elements themselves directly in the DOM. Maybe this question helps:

jQuery convert DOM element to different type

安静被遗忘 2024-09-09 21:06:29

很简单

$(this).attributes();将为您提供每个实例的 i 标记的所有属性,只需将其放入您的替换函数中即可。

我不确定你如何使用一个函数,但据我所知,代码将是这样的。

$("i").each(function(){
var 属性 = $(this).attributes();
$(this).replaceWith($(''

+ this.innerHTML + ''));
});

希望有帮助。

It is simple

$(this).attributes(); will get you all the attributes of the i tag for every instance simply place it into your replace function.

I am not sure how can you play with a function but in my knowledge code will be something like this.

$("i").each(function(){
var attribute = $(this).attributes();
$(this).replaceWith($('<em'+attributes+'>'

+ this.innerHTML + ''));
});

Hope it helps.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文