2016-01-13 95 views
-1

如何使用jQuery獲取父ID?

$('td').click(function() { 
 
    myId = $(this).parent().attr("id"); 
 
    myItem = $(this).text(); 
 
    alert('u clicked ' + myId); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> 
 
<table> 
 
    <tr> 
 
    <td>Computer</td> 
 
    </tr> 
 
    <tr> 
 
    <td>maths</td> 
 
    </tr> 
 
    <tr> 
 
    <td>physics</td></div> 
 
    </tr> 
 
</table>

當我點擊表項我想警告'u clicked science'但我得到undefined

任何幫助,將不勝感激!

+0

嘗試,警報( 'U點擊' + myItem); – Ravneet

+2

爲什麼我在html中看不到任何'id's? – Rajesh

+0

請編輯您的問題以顯示外部html - 您當前的代碼不顯示任何id屬性或任何地方的字符串「science」。我想那包含在一個parenet元素中,但要回答我需要看到這個元素 – Steve

回答

2

您的markup中沒有id屬性。所有你面對的是innerText

$('td').click(function() { 
 

 
    var myItem = $(this).text(); 
 
    alert('u clicked ' + myItem); 
 

 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> 
 
<table> 
 
    <tr> 
 
    <td>Computer</td> 
 
    </tr> 
 
    <tr> 
 
    <td>maths</td> 
 
    </tr> 
 
    <tr> 
 
    <td>physics</td> 
 
    </tr> 
 
</table>

+0

'「你點擊科學」'強烈表明有一個父元素沒有在問題中顯示。 「科學」沒有出現在任何文本節點中,加上「計算機,數學和物理學」都可以被寬鬆地認爲是科學領域,但最終是任何人的猜測,除非OP響應 – Steve

1

你有無效的標記。在最後的tr閉幕標記之後添加額外的閉合div。你需要刪除它。

你需要提醒的是元素的文本,而不是父母的ID。使用.text()與點擊td元素的jQuery上下文一起:

$('td').click(function(){ 
 
myItem=$(this).text(); 
 
alert('u clicked ' +myItem); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> 
 
<table> 
 

 

 
<tr><td>Computer</td></tr> 
 

 

 
<tr><td>maths</td></tr> 
 

 
<tr><td>physics</td></tr> 
 

 
</table>

0

試試這個:

$('td').click(function() { 
     alert('u clicked ' + $(this).text()); 
    }); 
0

正如我已經評論說,你缺少IDtr。我已經添加了幾個td的演示。

$('td').click(function() { 
 
    var myId = $(this).parent().attr("id"); 
 
    var myItem = $(this).text(); 
 
    alert('u clicked ' + myId); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> 
 
<table> 
 
    <tr id="IT"> 
 
    <td>Computer</td> 
 
    </tr> 
 
    <tr id="General"> 
 
    <td>maths</td> 
 
    <td>History</td> 
 
    </tr> 
 
    <tr id="Science"> 
 
    <td>physics</td> 
 
    <td>Chemistry</td> 
 
    <td>Biology</td> 
 
    </tr> 
 
</table>