2014-09-06 106 views
2

我試圖捕獲當用戶點擊允許他離開頁面的元素時被點擊元素的ID。這個想法是,然後使用Ajax記錄。下面的腳本似乎工作正常,只要元素有一個ID,但它似乎無法爬到DOM找到祖先的ID,如果它沒有。我究竟做錯了什麼?點擊元素的jQuery捕獲ID

$(document).ready(function(){ 
    $('a, button, input[type=submit]').on('click', function (event) { 
     if (event.target.id == '') 
      alert($(this).closest('[id!=""]').attr('id')); 

     else 
      alert(event.target.id); 
    }); 
}); 
+1

這裏的代碼工作正常,http://jsfiddle.net/BrianDillingham/bg91uqpm/也許它如何綁定事件 – 2014-09-06 16:41:10

+0

@Brian它不能正常工作,如果ID屬性不存在於點擊的元素作爲代碼只檢查一個空字符串 – 2014-09-06 16:54:51

+0

它在我的演示 – 2014-09-06 16:57:38

回答

1

如果父母的ID沒有被定義或元素嵌套這麼多,你不能怎麼算許多父母它,即得到最接近的父母的ID實際上有一個ID,那麼這段代碼將爲你做這項工作:DEMO

$(document).on('click', 'a, button, [type="submit"]', function() { 

    if($(this).attr('id') === undefined || $(this).attr('id') === null) { 
     alert($(this).parents().filter(function(){ 
      return $(this).attr('id')!=undefined && $(this).attr('id')!=null; 
     }).attr('id')); 
    } else { 
     alert($(this).attr('id')); 
    } 

}); 
+0

輝煌,謝謝! – 2014-09-06 16:55:43

+0

不客氣;) – 2014-09-06 16:55:56

1

我相信這將遞歸找到標識

$(document).on('click', 'a, button, [type="submit"]', function() { 

    findID($(this)); 

}); 

function findID(element) { 
    if(element.attr('id') === undefined || element.attr('id') === null) { 
     var temp = element.parent().attr('id'); 
     if(temp === undefined || temp === null){ 
      findID(element.parent()); 
     } else { 
      alert(temp); 
     } 
    } else { 
     alert(element.attr('id')); 
    } 
} 

DEMO

+0

如果父元素還沒有一個ID呢? – 2014-09-06 16:27:08

+0

然後你必須使用函數遞歸地解析DOM元素。但我認爲這個問題已經超出了範圍。 – cs1193 2014-09-06 16:28:53

+0

相反,我相信這正是OP所要求的,找到與ID最近的容器,所以實際上有東西要記錄 – 2014-09-06 16:33:50

1

這裏的方式通過DOM遞歸地尋找一個ID attribut:

$(document).ready(function() { 
     $('a, button, input[type=submit]').on('click', function (event) {    
      getID($(this)); 
     }); 

     function getID(element) { 
      if (element.attr('id') && element.attr('id') !== "") { 
       alert(element.attr('id')); 
      } else if (element.parent()) { 
       getID(element.parent()); 
      } 
     } 
    }); 
1

的問題與您的代碼是,你如果點擊的元素的id屬性是空只檢查但你並沒有檢查它是否真的存在。此外,它似乎[id!=""]選擇工作不正常,但我發現,添加[id]之前迫使元素有一個ID使得它的工作,所以更簡潔的解決辦法是這樣的:

$(document).ready(function(){ 
    $('a, button, input[type=submit]').on('click', function() { 
     var id = this.id ? this.id : $(this).closest('[id][id!=""]').attr('id'); 
     alert(id); 
    }); 
}); 

Demo fiddle