2017-04-21 29 views
2

我使用下面的代碼嘗試從另一個元素獲取href數據,它不斷返回「undefined」我做錯了什麼?從兄弟的孩子jQuery獲取href屬性?

$('.linkbutton').bind('click', function(e) { 
     e.preventDefault(); 
     var flagURL = $(this).siblings().next('.flag-action').attr('href'); 
     console.log(flagURL); 
    }); 
<div class="linkbutton"> 
<h4 class="quoteflag"> 
    <a href="/demo/url/here" title=" " class="flag-action"> 
    </a> 
</h4> 
+0

'兄弟姐妹()'給你從同一拉特作爲選定元素的所有元素,所以你選擇'.linkbutton'嘗試從同一拉特選擇所有元素,然後選擇帶有標誌動作類的下一個元素,詳細瞭解https://api.jquery.com/siblings/和https://api.jquery.com/each/ – Sojtin

回答

0

代替

var flagURL = $(this).siblings().next('.flag-action').attr('href'); 

試試下面的代碼:

var flagURL = $(this).siblings().find('.flag-action').attr('href'); 

因爲next()的選擇將返回你的下一個同級。但你需要下一個兄弟姐妹的孩子。 Find()選擇器會給你一個特定元素的所有後代。在你的情況下,你可以使用children()選擇器而不是find(),因爲你正在試圖找到H4元素的直接子元素。

3

你將不得不使用.find(),而不是.next()因爲flag-action是一個孩子,而不是一個元素旁邊的quoteflag

$('.linkbutton').bind('click', function(e) { 
 
    e.preventDefault(); 
 
    var flagURL = $(this).siblings().find(".flag-action").attr("href"); 
 
    console.log(flagURL); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="linkbutton">click</div> 
 
<h4 class="quoteflag"> 
 
    <a href="/demo/url/here" title=" " class="flag-action"> 
 
    </a> 
 
</h4>

1

您可以通過使用find('.flag-action')作爲a得到href是一個孩子的.linkbutton like:

$('.linkbutton').bind('click', function(e) { 
 
     e.preventDefault(); 
 
     var flagURL = $(this).find('.flag-action').attr('href'); 
 
     alert(flagURL); 
 
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<div class="linkbutton">Click here 
 
<h4 class="quoteflagdiv"> 
 
    <a href="/demo/url/here" title=" " class="flag-action"> 
 
    </a> 
 
</h4>

0

$('.linkbutton').bind('click', function(e) { 
 
     e.preventDefault(); 
 
     
 
     var flagURL = $(this).siblings().find('.flag-action').attr('href'); 
 
     console.log(flagURL); 
 
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="linkbutton">linkbutton div</div> 
 
<h4 class="quoteflag"> 
 
    <a href="/demo/url/here" title=" " class="flag-action"> 
 
    </a> 
 
</h4>