添加自定义属性以更好地分离 JavaScript 和 HTML

Adding a custom attribute for a better separation between JavaScript and HTML

本文关键字:JavaScript HTML 分离 自定义属性 更好 添加      更新时间:2023-09-26

使用 jQuery 和 backbone.js,我想尽可能地将 JavaScript 与 HTML 分开。
是否可以添加一个custom attribute以更好地区分JavaScript和HTML?然后如何使用新的jQuery选择器?

例:

<input type="text" id="todo-input" class="todo-input" tid="tid-attribute" > hello world </input>
// The DOM events
// I would like to use another selector tid and not class or id
events: {
  "keypress #todo-input" : "updateOnEnter" // I would like to use another selector tid not id,
  "keypress .todo-input" : "updateOnEnter" // I would like to use another selector tid and not class
}

HTML5 允许以 data- 开头的自定义数据属性:

<input type="text" data-custom-attr="somevalue">

然后在您的主干事件声明中:

"keypress [data-custom-attr='somevalue']" : "updateOnEnter"

您可以使用:

$('input[type="text"]').attr('tid', 'tid-attribute');

$('input[type="text"]').attr('data-tid', 'tid-attribute');