Javascript Jquery 自定义属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4145636/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 11:05:28  来源:igfitidea点击:

Jquery custom attributes

javascriptjquerycss

提问by Jose3d

I'm thinking about using custom attributes in Jquery to avoid using class or id attributes, to not interfere with the html designers.

我正在考虑在 Jquery 中使用自定义属性来避免使用 class 或 id 属性,以免干扰 html 设计器。

Taking into account this idea, the html should be pieces like:

考虑到这个想法,html 应该是这样的:

<ul Jquery="CommonUl">
    <li Jquery="CommonLi"></li>     
    <li Jquery="CommonLi"></li>
    <li Jquery="CommonLi"></li>
    <li Jquery="CommonLi"></li>
    <li Jquery="CommonLi"></li>
</ul>
  • Do you think this is a good approach?

  • What is your opinion about the W3C validation of these custom attributes?

  • Do you know any way to program with Jquery without interfering with the work of the html designers?

  • About the performance, I suppose that with class attributes or ids the jquery selectors are faster than using a custom attribute and filtering functions like "contains, etc...". Is this right?

  • 你认为这是一个好方法吗?

  • 您对这些自定义属性的 W3C 验证有何看法?

  • 你知道有什么方法可以用 Jquery 编程而不干扰 html 设计者的工作吗?

  • 关于性能,我认为使用类属性或 id,jquery 选择器比使用自定义属性和过滤功能(如“包含等...”)更快。这是正确的吗?

回答by Nick Craver

You can do this, use data-attributesthough (part of the HTML5 specification), like this:

您可以这样做,但使用data-属性HTML5 规范的一部分),如下所示:

<li data-something="CommonLi"></li> 

jQuery even has built-in support for these in 1.4.3+, for example:

jQuery 甚至在 1.4.3+ 中内置了对这些的支持,例如:

$("li").data("something") //"CommonLi"

For your other questions:

对于您的其他问题:

  • They'll validateif it's HTML5 - but won't breakanything in HTML4
  • This shouldn't interfere with the designer, but it'll depend on whichdesigner
  • If you're fetching from an element, the performance is the same as any other attribute
  • 他们会验证它是否是 HTML5 - 但不会破坏HTML4 中的任何内容
  • 这不应该干扰设计师,但这取决于哪个设计师
  • 如果您从元素中获取,则性能与任何其他属性相同

回答by Jose3d

if you're planning to have several attribute I suggest to set a unique namespaced attribute, e.g.

如果您打算拥有多个属性,我建议设置一个唯一的命名空间属性,例如

<li data-yourapp>...</li>

and use that attribute like an hashtable

并像哈希表一样使用该属性

$("li").data("yourapp", { 
   points  : 2000,
   life    : 1,
   weapons : {
      firegun  : 0,
      missiles : 12
   }
});

in this way you will reduce element access and you will retrieve all custom data once

通过这种方式,您将减少元素访问,并且您将检索所有自定义数据一次

回答by Zain Shaikh

I would personally recommend you to using jquery builtin method for saving data with each element. following is the code snippet for saving data:

我个人建议您使用 jquery 内置方法来保存每个元素的数据。以下是保存数据的代码片段:

$("ul").data("CommonUl");
$("li").data("CommonLi");