【问题标题】:jQuery capturing ID of a clicked object [duplicate]jQuery捕获单击对象的ID [重复]
【发布时间】:2013-12-27 09:26:03
【问题描述】:

我正在尝试检索我点击的元素的 ID

$mainBox.on('click', '.menuBtn', function(event) {
    console.log(event.target.attr('id'))    
});

我单击的元素作为外部 html 的一部分加载,这将是被单击的行:

<li class="menuBtn" id="item03"><span class="styleClass1">03</span><span class="styleClass2">Menu Item</span></li>

我如何获得item03? event.target.attr('id') 不这样做

【问题讨论】:

    标签: jquery jquery-selectors


    【解决方案1】:

    试试event.target

    event.target 是 DOM 元素,因此您需要将其设为 jQuery 对象才能使用.attr()


    $mainBox.on('click', '.menuBtn', function(event) {
        console.log($(event.target).attr('id'))    
    });
    


    或者直接使用 JavaScript
    $mainBox.on('click', '.menuBtn', function(event) {
        console.log(event.target.id);
    });
    

    $mainBox.on('click', '.menuBtn', function(event) {
        console.log(this.id);
    });
    

    this

    【讨论】:

    • @user3024007 Welocme 很高兴为您提供帮助 :)
    • 顺便说一句,它读作字符串吗?如果我将它传递给函数以加载一些与此 ID 匹配的内容,这会起作用吗? $('#foo').load ('external.html' + [passed data from this.id]) 哪里的 id 代表新加载的 html 中要抓取的元素?
    • @user3024007 this.id 将输出 id item03。您已将其与字符串示例 'ID is '+this.id+' you got it' 连接起来
    • 等等,我不确定我是否关注...假设我将 this.id 传递给函数...function(target) { $('#foo').load('external.html' '+target+ ')` ??
    • 非常感谢。我现在明白了
    猜你喜欢
    • 2020-03-30
    • 2020-02-28
    • 1970-01-01
    • 2012-03-04
    • 2018-10-17
    • 2013-12-07
    • 2017-04-29
    • 1970-01-01
    相关资源
    最近更新 更多