2016-12-02 82 views
-8

這裏是我的HTML:獲取IMG ALT其父的href東西

<div class="related-posts"> 
    <a href="http://localhost"> 
     <img width="100" height="100" src="test.jpg" alt="alt"> 
    </a> 
    <a href="http://localhost/1"> 
     <img src=" test1.jpg" alt="Hello world!"> 
    </a> 
</div> 

我需要得到alt價值img的其父是ahttp://localhost一個href。我可以使用哪些代碼來獲得該值?

+3

這是一個無效的HTML,沒有關閉img標籤。檢查。 –

+4

你卡在哪裏? jQuery的文檔(和CSS的文檔)對於如何基於屬性值查找元素以及如何查找其他元素的後代元素十分清楚。 –

+0

謝謝,但現在我無法編輯在計算器中的代碼。在我的本地通常是 –

回答

3
// will match http://localhost only: 
$('a[href="http://localhost"]').find('img').attr('alt'); 

// will match links hreffing to URLs starting with http://localhost 
$('a[href^="http://localhost"]').find('img').attr('alt'); 
+1

這可能會變小:'$(「a [href * ='http:// localhost']> img」).attr(「alt」);' – Roberrrt

+1

假設** direct **子結構不改變,是的。 – connexo

+0

也許OP想要嚴格匹配屬性值,但這不是很清楚,所以...你得到我的投票 –