简体   繁体   English

使用非标准属性

[英]Using non-standard attributes

I am having trouble passing around values without using global variables when I am creating html/jquery applications. 创建html / jquery应用程序时,我无法在不使用全局变量的情况下传递值。 Quick example 快速示例

1) Load a table with a class such as "playersTable" 1)加载带有“ playersTable”之类的表

2) Attach a unique ID such as "25" 2)附加一个唯一的ID,例如“ 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; 3)点击表格行并产生一行按钮,这些按钮将根据父母的班级和ID来执行操作; such as query playersTable WHERE row = 25, etc. 例如查询playerTable WHERE行= 25,等等。

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 问题是,在开发过程中,我需要将越来越多的值绑定到父元素(或任何已经具有类和ID的元素),并且要避免在类中添加20件事

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? 还是我通常会以所有错误的方式来解决这个问题?

Without knowing why you need to attach all that data to DOM elements it's hard to give concrete advice. 不知道为什么需要将所有这些数据附加到DOM元素上,很难给出具体的建议。

First, I'd consider using data- attributes. 首先,我会考虑使用data-属性。

Second, I'd consider using jQuery's data() method if you're attaching the data dynamically. 其次,如果要动态附加数据,我会考虑使用jQuery的data()方法。

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. 第四,也是最重要的一点,ID属性可能并不是您真正想要设置的。

Use a data-id element and get the ID that way; 使用data-id元素并以这种方式获取ID; a simple numeric value isn't a valid ID. 简单的数字值不是有效的ID。 Unless you actually need to refer to the DOM element by ID, why bother? 除非您实际上需要通过ID引用DOM元素,否则何必呢? 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") . 通常,您真正需要的只是查找(或向下)附近的层次结构并找到父行等,以提取单个值,例如data("id")

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') . 我建议您将data- *属性与纯JavaScript element.getAttribute('data-some_attr_name')或与jQuery element.data('some_attr_name')

Browser support: http://caniuse.com/dataset 浏览器支持: http : //caniuse.com/dataset

jQuery data docs: http://api.jquery.com/data/ jQuery数据文档: http//api.jquery.com/data/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM