【问题标题】:Get <div> name using jQuery使用 jQuery 获取 <div> 名称
【发布时间】:2011-07-24 04:22:02
【问题描述】:
$("body").click(function() {
       var item = "<h1>You clicked on: #" + $(this).attr('id');
       $(".position").html(item);
     });

为什么这给了我一个空白的回复?我希望它识别每个被点击的 HTML 对象的 ID。

【问题讨论】:

    标签: jquery css html attr


    【解决方案1】:

    试试这个

    $("body").click(function(e) {
           var item = "<h1>You clicked on: #" + $(e.target).attr('id') + "</h1>";
           $(".position").html(item);
         });
    

    【讨论】:

      【解决方案2】:

      this 指的是您注册处理程序的对象,而不是事件的原始来源。
      在您的情况下,this 始终是 &lt;body&gt;

      你想要e.target,它指的是直接触发事件的元素。
      (其中e 是处理函数的第一个参数)

      【讨论】:

      • 请注意 e 将是事件处理程序中的一个参数。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-21
      • 2015-05-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多