javascript动态更改图像src的位置 - 没有JQuery [英] javascript dynamically change the location of image src - NO JQuery

查看:238
本文介绍了javascript动态更改图像src的位置 - 没有JQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以相同的方式设置了几个页面。每个页面包含大约10到15个图像,如果单击它们,图像将更改并变为不可点击。
我的代码是:

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";
}
}

图片的html为:

  ....
  <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>
   ....

因为我需要制作大约20个html文件,所以我有将图像的源位置添加为wrapper-div的id-tag的概念。

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.

我对javascript知之甚少,我很难找到什么我在找。可能也是因为我不是母语人士并且不知道我到底在想什么。

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.

请记住我的档案:


  1. 由于我们客户的规格,必须使用较旧的浏览器版本

  2. 无法使用JQuery修复(请不要在评论或答案中进入。我不能在这个项目中使用它。它不适合讨论。)

tldr;我需要一种基于wrapper-div的id-tag设置img src的方法

推荐答案

getElementsByClassName 给出一个集合而不是单个元素

getElementsByClassName gives a collection not a single element

将元素传递给 ToggleOnclick 所以你不会必须在函数中获取它

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);" />

这篇关于javascript动态更改图像src的位置 - 没有JQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆