簡體   English   中英

從觸發事件的元素返回屬性 id

[英]Return the attribute id from the element that triggered the event

我有一個元素,該元素通過以下代碼調用函數 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 中。 我該怎么做?

event.currentTarget不是一個 jQuery 對象,它是一個 DOM 節點。

var myIf = event.currentTarget.id;

event.currentTarget不是 jQuery 對象,所以attrundefined

您可以通過以下方式修復:

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

假設您的其余代碼按預期工作,我建議:

var myId = event.currentTarget.id;

因為它是一個普通的 DOM 節點,而不是一個 jQuery 對象,所以attr()方法不會也不能工作。

參考:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM