javascript 从触发事件的元素返回属性 id

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14223385/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 21:03:13  来源:igfitidea点击:

Return the attribute id from the element that triggerd the event

javascript

提问by Elian ten Holder

I have an element, this element calls the function calcTotal via the following code:

我有一个元素,该元素通过以下代码调用函数 calcTotal:

$('.pause').change(function(e) {
    window.alert("pause changed");
    calcTotal(e);

The code of calcTotal(e) is as follows:

calcTotal(e)的代码如下:

function calcTotal(event)
{   alert('calcTotal called');
    var myId = event.currentTarget.attr('id');

    myId = myId.replace(/[^0-9]/g, '');

    var timeRegex = /^[0-9]{1,2}:[0-9]{2}$/;

    if($('#start'+myId).val().match(timeRegex) && $('#end'+myId).val().match(timeRegex) && $('#pause'+myId).val().match(timeRegex))
    {
        var minutes = 0;

        var n = $('#end'+myId).val().split(':');
        minutes = parseInt(n[0])*60 + parseInt(n[1]);

        var n = $('#start'+myId).val().split(':');
        minutes -= parseInt(n[0])*60 + parseInt(n[1]);

        var n = $('#pause'+myId).val().split(':');
        minutes -= parseInt(n[0])*60 + parseInt(n[1]);

        var hours = Math.floor(minutes/60);
        minutes = minutes % 60;
        alert(hours + ':' + minutes);
        $('#total' + myId).val(hours + ':' + minutes);
    }
    else
    {       
        $('#total' + myId).val('00:00');
    }

}   

It doesn't work as I had exceptected and when I debug with firebug it says the following:

它无法正常工作,当我使用 firebug 进行调试时,它会显示以下内容:

TypeError: event.currentTarget.attr is not a function
var myId = event.currentTarget.attr('id');  

I would like to store the id of the element in myId. How would I do this?

我想将元素的 id 存储在 myId 中。我该怎么做?

回答by Niet the Dark Absol

event.currentTargetis not a jQuery object, it's a DOM node.

event.currentTarget不是一个 jQuery 对象,它是一个 DOM 节点。

var myIf = event.currentTarget.id;

回答by Ricardo Alvaro Lohmann

event.currentTargetisn't a jQuery object, so attris undefined.

event.currentTarget不是一个 jQuery 对象,所以attrundefined.

You can fix by the following ways:

您可以通过以下方式修复:

$(event.currentTarget).attr('id');
event.currentTarget.id;

回答by David says reinstate Monica

Assuming the rest of your code works as intended, I'd suggest:

假设您的其余代码按预期工作,我建议:

var myId = event.currentTarget.id;

Because it's a plain DOM node, not a jQuery object, the attr()method won't, and can't, work.

因为它是一个普通的 DOM 节点,而不是一个 jQuery 对象,所以该attr()方法不会也不能工作。

References:

参考: