2013-08-30 47 views
0

請幫我創建一個函數,其中包括多個變量 - 至少兩個......的onclick多變量

我已經將其用PHP和MySQL創建表......所有的ID都dinamically創建爲什麼我需要以其他方式抓住他們而不是指定他們。

爲了更好地理解表的結構一小塊代碼 - 我已經包含在jsFIDDLE

function delete_id(id) { 
    alert (id); 
    var test = $(this).closest('tr').attr('id'); 
    alert(test); 
}; 
+0

檢查我的答案。 –

回答

2

試試這個:

var test = $('#'+id).closest('tr').attr('id'); 

$(this)在你的功能並不意味着你在想什麼。您需要使用您傳遞到functionid並獲得該元素與$('#'+id)

演示here

+0

確實 - 很酷!謝謝!!! –

1

我相信使用上是一個好方法這裏使用的委託。就好像我們使用它,它不會將事件冒泡到文檔,也不會爲所有tr創建儘可能多的點擊處理程序,或者在DOM中的這些動態tr之下創建一個總體上對性能有好處的標記。

$(document).ready(function(){ 
    $('.ultomonitor').on('click','a', function(){ 
    alert("id of div under a " + $(this).children().attr('id')); 
    alert("id of tr above a " + $(this).closest('tr').attr('id')); 
    }); 
}); 

Working Demo

1

更好的辦法

DEMO

HTML

<a href="#"><div id="8928392" onclick="delete_id(this)" 

JS

function delete_id(el) { 
    var test = $(el).closest('tr').attr('id'); 
    alert(test); 
}; 

純JavaScript方式

DEMO

function delete_id(el) { 
    var test = getNearestTableRowAncestor(el).id; 
    alert(test); 
}; 

function getNearestTableRowAncestor(htmlElementNode) { 
    while (htmlElementNode) { 
     htmlElementNode = htmlElementNode.parentNode; 
     if (htmlElementNode.tagName.toLowerCase() === 'tr') { 
      return htmlElementNode; 
     } 
    } 
    return undefined; 
} 
+0

我需要爲jquery/Ajax函數保持這個簡單 - 非常感謝您的方法! –

+0

@SergiuCostas這是比答案更好的方法 - > http://jsfiddle.net/cse_tushar/UcCeW/31/ –

+0

在我的情況下,我需要兩個ID ...答案給了我解決方案,在函數中接收ID ...在你的情況 - 我只有從的ID ...但無論如何不錯的方法..非常感謝你!我會從你的經驗中學習! –