10

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

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

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');
    }

}   

它不起作用,因为我已经例外,当我使用 firebug 进行调试时,它显示以下内容:

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

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

4

3 回答 3

20

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

var myIf = event.currentTarget.id;
于 2013-01-08T20:25:16.790 回答
11

event.currentTarget不是 jQuery 对象,attr所以undefined.

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

$(event.currentTarget).attr('id');
event.currentTarget.id;
于 2013-01-08T20:25:24.467 回答
3

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

var myId = event.currentTarget.id;

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

参考:

于 2013-01-08T20:25:18.603 回答