如何在javascript中访问<img/>标签的'src'属性?

时间:2012-06-25 04:00:18

标签: javascript

<html>
<head></head>
<body>
<div id="ctl00_ContentPlaceHolder1_ctl00_ctl01_Showcase">
<div style="width:100%;text-align:center;"><img src="http://www.xyz.com/aaa.gif" id="ctl00_ContentPlaceHolder1_ctl00_ctl01_loderImg" alt="Loading" /></div>        </div>
<script>
q= document.getElementById('ctl00_ContentPlaceHolder1_ctl00_ctl01_Showcase').childNodes[1].getAttribute('src').innerHTML;

alert(q);

</script>
</body>
</html>

如何访问img标签的'src'属性?我上面的代码它给出了空值,所以什么是错的?

4 个答案:

答案 0 :(得分:12)

您可以直接在图片上使用src。此外,您不需要.innerHTML

演示:http://jsfiddle.net/ThinkingStiff/aU2H2/

document.getElementById( 'ctl00_ContentPlaceHolder1_ctl00_ctl01_loderImg' ).src;

HTML:

<html>
<head></head>
<body>
<div id="ctl00_ContentPlaceHolder1_ctl00_ctl01_Showcase">
    <div style="width:100%;text-align:center;"><img src="http://placekitten.com/100/100" id="ctl00_ContentPlaceHolder1_ctl00_ctl01_loderImg" alt="Loading" /></div>        
</div>
<script>
    q = document.getElementById( 'ctl00_ContentPlaceHolder1_ctl00_ctl01_loderImg' ).src;
    alert(q);
</script>
</body>
</html>

答案 1 :(得分:5)

alert(document.getElementById('your_image_id').getAttribute('src'));

答案 2 :(得分:0)

首先,你不应该在最后使用.innerHTML,因为属性没有innerHTML数据。其次,JS在涉及空白时如何处理儿童是非常脆弱的。我会建议像其他人指出的那样通过ID定位图像。或者你可以使用这样的东西:

q= document.getElementById('ctl00_ContentPlaceHolder1_ctl00_ctl01_Showcase').getElementsByTagName("img")[0].getAttribute("src");

引用 ctl00_ContentPlaceHolder1_ctl00_ctl01_Showcase 节点,然后找到它下面的图像。

答案 3 :(得分:0)

使用jQuery

var imgsrc = $("#ctl00_ContentPlaceHolder1_ctl00_ctl01_loderImg").attr("src");

jQuery是IMO最强大的方式。