Javascript 如何在javascript中访问<img>标签的'src'属性?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11183368/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do i access 'src' attribute of <img> tag in javascript?
提问by Pooja Desai
<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>
how do i access 'src' attribute of img tag ? im above code it gives null value so whats wrong ?
我如何访问 img 标签的“src”属性?我上面的代码给出了空值,所以出了什么问题?
回答by ThinkingStiff
You can use src
on your image directly. Also, you don't need .innerHTML
.
您可以src
直接在图像上使用。此外,您不需要.innerHTML
.
Demo: http://jsfiddle.net/ThinkingStiff/aU2H2/
演示:http: //jsfiddle.net/ThinkingStiff/aU2H2/
document.getElementById( 'ctl00_ContentPlaceHolder1_ctl00_ctl01_loderImg' ).src;
HTML:
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>
回答by coolguy
alert(document.getElementById('your_image_id').getAttribute('src'));
回答by Matt Wolfe
First off, you shouldn't use .innerHTML at the end as attributes don't have innerHTML data. Secondly, JS is very fragile with how it handles children when it comes to whitespace. I would recommend targeting the image by ID as others have pointed out. Alternatively you could use something like this:
首先,您不应该在最后使用 .innerHTML,因为属性没有 innerHTML 数据。其次,JS 在处理空白时非常脆弱。正如其他人指出的那样,我建议按 ID 定位图像。或者你可以使用这样的东西:
q= document.getElementById('ctl00_ContentPlaceHolder1_ctl00_ctl01_Showcase').getElementsByTagName("img")[0].getAttribute("src");
to reference the ctl00_ContentPlaceHolder1_ctl00_ctl01_Showcasenode and then find the image underneath it.
引用ctl00_ContentPlaceHolder1_ctl00_ctl01_Showcase节点,然后找到它下面的图像。