Using non-standard attributes

人走茶凉 提交于 2021-02-05 07:09:55

问题


I am having trouble passing around values without using global variables when I am creating html/jquery applications. Quick example

1) Load a table with a class such as "playersTable"

2) Attach a unique ID such as "25"

3) Click on the table row and spawn a row of buttons that will perform actions based on the parent's class and ID; such as query playersTable WHERE row = 25, etc.

The issue is that, as I am developing, I need to tie more and more values to the parent element (or any element that already has a class and ID) and I want to avoid adding 20 things to the class

I don't know what to do when I need to attach even more data to my elements. I have also made use of the attribute "value" but then I wonder if all browsers support it, if it's bad practice, etc. Does it even work if I just start creating my own attributes? Such as

<div id = "2" class = "test" myAttr = "foo"></div>

Or am I going about this all the wrong way in general?


回答1:


Without knowing why you need to attach all that data to DOM elements it's hard to give concrete advice.

First, I'd consider using data- attributes.

Second, I'd consider using jQuery's data() method if you're attaching the data dynamically.

Third, I'd consider what data you actually need, and when.

Fourth, and probably most importantly, the ID attribute probably isn't really what you want to be setting.

Use a data-id element and get the ID that way; a simple numeric value isn't a valid ID. Unless you actually need to refer to the DOM element by ID, why bother? Usually what you really need is to just look up (or down) the nearby hierarchy and find the parent row etc. to pull out a single value, like data("id").




回答2:


I recommend you to use data-* attributes, either with pure JavaScript element.getAttribute('data-some_attr_name') or with jQuery element.data('some_attr_name').

Browser support: http://caniuse.com/dataset

jQuery data docs: http://api.jquery.com/data/



来源:https://stackoverflow.com/questions/24844785/using-non-standard-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!