所以我有一组生成的 div,其中包含一个名为“class1”的类。我需要能够为它们分配一个名称或 ID,然后使用 JQuery 来注册我已经单击了这些 div 中的特定一个。我有这段代码,但这不起作用,因为我所知道的就是选择类名:
jQuery(".class1").click(function () {
// do something
});
我需要能够获取所单击的 div 的唯一标识符并将其用于某些用途
最佳答案
要访问单击的元素的 id,您可以访问 this
的 id
属性,该属性具有单击的 HTML 元素的上下文。
jQuery(".class1").click(function () {
// do something
var theId = this.id; // contains the id of the clicked element, assuming is has an id.
});
您提到动态元素,在这种情况下,您需要在添加元素后绑定(bind)事件或通过委托(delegate)进行绑定(bind)。
对于 jQuery 1.7 及更高版本,请使用 on() :
jQuery("body").on("click", ".class1", function () {
// do something
var theId = this.id;
});
对于 jQuery 1.6 及更早版本的使用,delegate() :
jQuery("body").delegate(".class1", "click", function () {
// do something
this.id;
});
关于javascript - 获取在 JQuery 中单击的动态 div 的名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15510860/