javascript dynamically change the location of image src - NO JQuery

空扰寡人 提交于 2019-12-12 17:22:55

问题


I have several pages set up in the same way. Each page has about 10 to 15 images and if you click them, the image changes and becomes unclickable. The code I have for this is:

function ToggleOnclick(elID)
{
var el = document.getElementById(elID);
var loc = document.getElementsByClassName("wrapper");

if (el.onclick)
{
        // Disable the onclick
        el._onclick = el.onclick;
        el.onclick = null;
        el.src = loc.id + "/" + el.name + "Clicked.png";
}
}

The html for the images is:

  ....
  <div class="content">
   <div class="wrapper" id="som">
   <div class="img0"><img src="som/doos.png" alt="doos" name="doos" id="doos" onclick="ToggleOnclick(this.name);" /></div>
   <div class="img1"><img src="som/beer.png" alt="beer" name="beer" id="beer" onclick="ToggleOnclick(this.name);" /></div>
   <div class="img2"><img src="som/bel.png" alt="bel" name="bel" id="bel" onclick="ToggleOnclick(this.name);" /></div>
   ....

Because I need to make about 20 html-files, I had the notion to add the source location of the images as the id-tag of the wrapper-div.

I have little knowledge of javascript and I have a hard time finding what I'm looking for. Possibly also due to not being a native speaker and not knowing what I'm looking for exactly.

Please bear in mind that my files:

  1. have to work in older browser versions due to the specs of our customers
  2. can't be fixed with JQuery (Please don't go into that in comments or answers. I can't use it in this project. It's not up for discussion.)

tldr;I need a way to set the img src based on the id-tag of the wrapper-div


回答1:


getElementsByClassName gives a collection not a single element

pass the element to ToggleOnclick so you won't have to fetch it in the function

function ToggleOnclick(el)
{
//var loc = document.getElementsByClassName("wrapper")[0];//assuming there is only one wrapper
if (el.onclick)
{
        // Disable the onclick
        el._onclick = el.onclick;
        el.onclick = null;
        //el.src = loc.id + "/" + el.name + "Clicked.png";
        el.src = el.src.replace(".png", "Clicked.png");
}
}
<img src="som/doos.png" alt="doos" name="doos" id="doos" onclick="ToggleOnclick(this);" />


来源:https://stackoverflow.com/questions/11930079/javascript-dynamically-change-the-location-of-image-src-no-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!