簡體   English   中英

如何從父元素獲取ID作為字符串並將其與另一個字符串進行比較?

[英]How to get the ID as a string from a parent element and compare to another string?

我有以下HTML結構:

<div id="blah">
    <ul style="...">
        <li><a href="...">...</a></li>
    </ul>
</div>

我有一個針對所有<a>標簽的jQuery選擇器。 但是,我想檢查單擊的<a>是否為id="blah"的子項。

這是我到目前為止的內容:

$(document).on('click', 'a', function(t) {
    console.info($(this).text());
    if($(this).parent() == 'blah'){
        console.info('Yes, this link has the parent');
    }
});

但是, if永遠不會成為真,並且我無法檢測到鏈接何時具有指定的父級。 如何正確執行此操作?

使用attr()獲取元素屬性值

if($(this).parent() == 'blah'){

應該

if($(this).parent().attr('id') == 'blah'){

 $(document).on('click', 'a', function() { console.info($(this).text()); if ($(this).parent().attr('id') == 'blah') { console.info('Yes, this link has the parent'); } return false; // To stop page redirection }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="blah"> <ul style="..."> <li><a href="...">...</a> </li> </ul> </div> 


您也可以使用

if($(this).parent().is('#blah'){

我想檢查單擊的是否為id =“ blah”的子項。

if ($(this).parent('#blah').length) {

如果要檢查祖先 ,這將檢查直接父母

if ($(this).closest('#blah').length) {

暫無
暫無

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

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