close
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
span{
color: darkRed;
}
</style>
</head>
<body>
<img>
<button id="btn">按我就不同</button>
<h2 >有src這個屬性嗎<span id="now"></span></h2>
<h2>有的話,屬性值是<span id="value"></span></h2>
<script type="text/javascript">
var img=document.getElementsByTagName('img')[0];
document.getElementById('now').innerHTML=img.hasAttribute('src');
document.getElementById('btn').onclick=function(){
if(img.hasAttribute('src')){
img.removeAttribute('src');
}else{
img.setAttribute('src','https://api.fnkr.net/testimg/50x50/00CED1/FFF/?text=img');
}
document.getElementById('now').innerHTML=img.hasAttribute('src');
document.getElementById('value').innerHTML=img.getAttribute('src');
}
</script>
</body>
</html>
另外,
document.getElementsByTagName('img')[0]
也可寫成
document.getElementsByTagName('img').item(0)
全站熱搜
留言列表