原生js图片替换位置

原生js图片替换位置

 

 

<script>
function changeImg(id,img) {
document.getElementById(id).src =img;
}
</script>
<p><img src="https://www.baidu.com/img/baidu_jgylogo3.gif" id="baidu"/></p>
<p><img src="https://www.baidu.com/img/baidu_jgylogo3.gif" id="qihu"/></p>
<p>
<img src="https://www.baidu.com/img/bd_logo1.png?where=super" onclick="changeImg('baidu',this.src)" />
<img src="https://p.ssl.qhimg.com/t01e92920a7b90351cc.png" onclick="changeImg('qihu',this.src)" />
</p>

 

同步修改ID方法

<script>
function changeImg(sclass,sid,img) {
tclass = getElementsByClass(sclass);
tclass[0].src =img;
tid =tclass[0].getAttribute("id");
tclass[0].setAttribute("id",'s'+sid);
}

function getElementsByClass(classnames){
var classobj = new Array();
var classint = 0;
var tags =document.getElementsByTagName("*");
for(var i in tags){
if(tags[i].nodeType == 1){
if(tags[i].getAttribute("class") == classnames){
classobj[classint] = tags[i];
classint++;
}
}
}
return classobj;
}
</script>
<p><img src="https://www.baidu.com/img/baidu_jgylogo3.gif" id="baidu" class="baidu"/></p>
<p><img src="https://www.baidu.com/img/baidu_jgylogo3.gif" id="qihu" class="qihu"/></p>
<p>
<img src="https://www.baidu.com/img/bd_logo1.png?where=super" onclick="changeImg('baidu','12',this.src)" />
<img src="https://p.ssl.qhimg.com/t01e92920a7b90351cc.png" onclick="changeImg('baidu','13',this.src)" />
<img src="https://p.ssl.qhimg.com/t01e92920a7b90351cc.png" onclick="changeImg('qihu','23',this.src)" />
</p>