我可以在div上使用自定义属性吗? [英] Can I use a custom attribute on a div?

查看:810
本文介绍了我可以在div上使用自定义属性吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在jQuery中获取一个数字值,但是要使其正常工作,我需要在我的div上设置第3个属性.

I need to get a number value in jQuery, but for this to work I need a 3rd attribute on my div.

<div class="button" id="button$post" numberlk="$total">

这很好!但是HTML验证程序告诉我:

This works fine! But HTML the validator tells me:

错误:此时元素div上的属性numberlk不允许.

Error: Attribute numberlk not allowed on element div at this point.

我该怎么做才能使其正常工作?

What can I do to make it work correctly?

推荐答案

虽然可以在HTML中创建自己的属性,但您不应该这样做.这是因为它使HTML无效,这可能导致UI以及页面上运行的任何Javascript出现意外问题.

While it's possible to create your own attributes in your HTML, you shouldn't. This is because it renders your HTML invalid which can lead to unexpected issues with the UI and also any Javascript running on the page.

将自定义元数据存储在元素的HTML中的一种更好的方法是改用data属性,例如data-numberlk="$totallikes":

A much better approach to store custom metadata in an element's HTML is to use a data attribute instead, eg data-numberlk="$totallikes":

<div class="button" id="button$post" data-numberlk="$total">

然后您可以使用data()方法在jQuery中检索此值:

You can then retrieve this value in jQuery using the data() method:

var likes = $('.button').data('numberlk');

或使用普通JS:

var likes = document.querySelector('.button').dataset.numberlk;

这篇关于我可以在div上使用自定义属性吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆