2

所以我有一组生成的 div,其中包含一个名为“class1”的类。我需要能够为他们分配一个名称或 ID,然后使用 JQuery 来注册我点击了其中一个特定的 div。我有这段代码,但这不起作用,因为我所知道的只是选择类名:

jQuery(".class1").click(function () {
     // do something                    
});

我需要能够获取单击的 div 的唯一标识符并将其用于某些事情

4

2 回答 2

3

要访问被点击元素的 id,您可以访问其具有被点击 HTML 元素上下文的id属性。this

jQuery(".class1").click(function () {
     // do something                    
     var theId = this.id; // contains the id of the clicked element, assuming is has an id.
});

您提到动态元素,在这种情况下,您需要在添加元素后绑定事件或使用委托绑定。

对于 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;
});
于 2013-03-19T21:38:03.097 回答
1

如果您在 DOM 加载后生成类名.. 动态,那么您需要使用委托事件处理程序。

jQuery('body').on('click', '.class1', function() {

  // to assign name
  $(this).attr('name', 'someName');

  // to assign ID
  $(this).attr('id', 'someUniqueID');

  // to get

  this.id  //  to get id

  this.name // to get name

});

笔记:

在委托事件处理的情况下,您应该使用任何静态容器元素来.class1代替body. 这是有效和最好的方法。

于 2013-03-19T21:33:59.993 回答