我是 jQuery 的新手(1.5 个月),我发现自己养成了我不太喜欢的 PHP + jQuery 习惯。我想知道是否有人建议让事情变得更优雅。考虑以下我通过执行简单的 SQL 查询生成并用 PHP 回显的 HTML:
<div id='boat_1' class='boat speedboat'></div>
<div id='boat_2' class='boat dory'></div>
<div id='car_1' class='car racecar'></div>
<div id='car_2' class='car racecar'></div>
如您所见,我选择了遵循 {type}_{id}
的 id
命名约定。现在,在 jQuery 中,假设我想将点击处理程序绑定(bind)到这些 car div。记住它们是动态的并且可以有任意数量,我会执行:
$(".car").bind('click', function(){
//do something
});
但通常情况下,//do something
想知道是哪辆车触发了点击事件。此外,//do something
可能需要将类型(船或汽车)和 id
分开以执行 POST 操作并写回数据库... (例如)
我现在正在做的查找 ID(以及我需要的其他唯一信息)的工作很简单,但对我来说,它闻起来像:
$(".car").bind(function(){
var id = $(this).attr("id").replace("car_", "");
});
有人可能会建议改用类属性,因为您不必担心唯一性。但是因为类名不是单数的(如我所示,每个元素可以有多个),我不认为这是一个候选解决方案。
因为 id 在整个文档中必须是唯一的,所以这是我已经解决的解决方案。我知道如果可以使用同名的多个 ID,getElementById() 会中断,但有时我想知道如果 ID 不必是唯一的,只要它们有不同的父级,这是否会有益。
你是怎么做到的?
我应该使用 HTML5 的 data-*
吗?
谢谢!
最佳答案
是的。
像这样呈现 HTML:
<div data-id="1" class="boat speedboat"></div>
<div data-id="2" class="boat dory"></div>
<div data-id="1" class="car racecar"></div>
<div data-id="2" class="car racecar"></div>
Jquery 处理程序
$(".car").bind(function(){
var $this=$(this);
var id = $this.data("id");
});
As of jQuery 1.4.3 HTML 5 data- attributes will be automatically pulled in to jQuery's data object. The treatment of attributes with embedded dashes was changed in jQuery 1.6 to conform to the W3C HTML5 specification.
关于jquery - 在 HTML 中适本地分配 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6622657/