![](/img/trans.png)
[英]how to modify the value of src attribute of <img> tag using jquery or javascript
[英]How do i access 'src' attribute of <img> tag in 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'屬性? 我上面的代碼它給出了空值,所以什么是錯的?
您可以直接在圖像上使用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>
alert(document.getElementById('your_image_id').getAttribute('src'));
首先,你不應該在最后使用.innerHTML,因為屬性沒有innerHTML數據。 其次,JS在涉及空白時如何處理兒童是非常脆弱的。 我會建議像其他人指出的那樣通過ID定位圖像。 或者你可以使用這樣的東西:
q= document.getElementById('ctl00_ContentPlaceHolder1_ctl00_ctl01_Showcase').getElementsByTagName("img")[0].getAttribute("src");
引用ctl00_ContentPlaceHolder1_ctl00_ctl01_Showcase節點,然后找到它下面的圖像。
使用jQuery :
var imgsrc = $("#ctl00_ContentPlaceHolder1_ctl00_ctl01_loderImg").attr("src");
jQuery是IMO最強大的方式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.