如何使用 jquery 将特定元数据添加到具有 ID 的 div 中

发布于 2025-01-14 06:22:40 字数 291 浏览 3 评论 0原文

我试图弄清楚如何编写 jQuery 代码以将元数据插入到元素中,具体来说是: data-section-name="home"

我想将其插入到带有 ID 的 div 中home-section 的输出如下:

<div id="home-section" data-section-name="home">
  (some code here...)
</div>

我在 WordPress 中使用 divi 构建器

I am trying to figure out how to write jQuery code to insert meta data in to an element, specifically this: data-section-name="home"

I want to insert this in a div with an ID of home-section and the output would be like this:

<div id="home-section" data-section-name="home">
  (some code here...)
</div>

I am using a divi builder in Wordpress

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

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

发布评论

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

评论(1

苍景流年 2025-01-21 06:22:40

如果您需要 data 属性出现在 HTML 源代码中,请使用 attr()

$('#home-section').attr('data-section-name', 'home');

如果 data 属性将由 jQuery 库读取,那么您可以使用 < code>data() 方法,它的性能更高:

$('#home-section').data('section-name', 'home');

两种情况下的警告是确保您在任何库依赖的之前执行这行代码存在该 data 属性。

If you need the data attribute to appear in the HTML source use attr():

$('#home-section').attr('data-section-name', 'home');

If the data attribute is going to be read by a jQuery library then you can use the data() method instead, which is more performant:

$('#home-section').data('section-name', 'home');

The caveat in both cases is to ensure that you execute this line of code before whatever library depends on that data attribute being present.

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