使用非标准属性 [英] Using non-standard attributes

查看:48
本文介绍了使用非标准属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在创建 html/jquery 应用程序时在不使用全局变量的情况下传递值时遇到问题.快速示例

1) 加载一个表,类如playersTable"

2) 附加一个唯一的 ID,例如25"

3) 单击表格行并生成一行按钮,这些按钮将根据父级的类和 ID 执行操作;比如查询playersTable WHERE row = 25等

问题是,随着我的发展,我需要将越来越多的值绑定到父元素(或任何已经具有类和 ID 的元素),并且我想避免向类添加 20 项

当我需要将更多数据附加到我的元素时,我不知道该怎么做.我也使用了属性value",但是我想知道是否所有浏览器都支持它,如果这是不好的做法等等.如果我刚开始创建自己的属性,它甚至有效吗?比如

还是我一般都以错误的方式处理这件事?

解决方案

如果不知道为什么需要将所有数据附加到 DOM 元素,就很难给出具体的建议.

首先,我会考虑使用 data- 属性.

其次,如果您要动态附加数据,我会考虑使用 jQuery 的 data() 方法.

第三,我会考虑您实际需要哪些数据以及何时需要.

第四,可能也是最重要的,ID 属性可能并不是您真正想要设置的.

使用 data-id 元素并以这种方式获取 ID;简单的数值不是有效的 ID.除非您确实需要通过 ID 引用 DOM 元素,否则何必呢?通常,您真正需要的是向上(或向下)查找附近的层次结构并找到父行等以提取单个值,例如 data("id").

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?

解决方案

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").

这篇关于使用非标准属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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