如何使用父的id获取第n个img标签的src属性

时间:2015-12-29 07:19:12

标签: jquery html

我想获取img标记的src属性,该标记是span标记的第n个子标记。图像标签的数量不固定。

我只想要图片的src,这是span id = zipcard1的第n个孩子。就像我将2传递给n-child一样,src应该是“klematis1.jpg”。

<span id="zipcard1" >
    <img id="user_guess_img31" class="guess_card" src="klematis.jpg" />
    <img id="user_guess_img31" class="guess_card" src="klematis1.jpg" />
    <img id="user_guess_img31" class="guess_card" src="klematis2.jpg" />
    <img id="user_guess_img30" class="guess_card" src="klematis3.jpg" />
</span>

我试过以下代码但没有工作:

var img_tag=$("#zipcard1 img : nth-child(2) ").html();

2 个答案:

答案 0 :(得分:2)

您需要从选择器中删除空格,因为它用于搜索子元素。另外,如果您想阅读src,则应使用.attr()方法。

&#13;
&#13;
alert($("#zipcard1 img:nth-child(2) ").attr('src'))
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="zipcard1" >
    <img id="user_guess_img31" class="guess_card" src="klematis.jpg" />
    <img id="user_guess_img31" class="guess_card" src="klematis1.jpg" />
    <img id="user_guess_img31" class="guess_card" src="klematis2.jpg" />
    <img id="user_guess_img30" class="guess_card" src="klematis3.jpg" />
</span>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

您可以使用eq()

function getSrc(index) {
  var src = $('#zipcard1 img').eq(--index).attr('src');
  alert(src);
}
getSrc(2);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="zipcard1">
    <img id="user_guess_img31" class="guess_card" src="klematis.jpg" />
    <img id="user_guess_img31" class="guess_card" src="klematis1.jpg" />
    <img id="user_guess_img31" class="guess_card" src="klematis2.jpg" />
    <img id="user_guess_img30" class="guess_card" src="klematis3.jpg" />
</span>