尝试通过PHP / Javascript / HTML更改图像onclick

时间:2017-05-16 18:19:25

标签: javascript php jquery html css

我已经看过很多关于此问题的其他答案,但还没有找到有效的解决方案。我正在使用包含一些HTML代码的PHP页面,Javascript正在运行一些功能。理想情况下,我会在页面上选择一个图像,图像将在选中时变为绿色。然后我想取消选择图像并让它恢复到原始状态。但是,我只能在那里中途。我错过了什么?这是回帖吗?

以下是一些代码示例:
HTML:
<div onclick="changeImage(1)" id="toolDiv1"><img id="imgCh1" src="/images/Tooling/1.png"></div>

Javascript功能:

        function changeImage(var i){
            var img = document.getElementById("imgCh" + i + ".png");

            if (img.src === "images/Tooling/" + i + ".png"){
                img.src = "images/Tooling/" + i + "c.png";
            }
            else
            {
                img.src = "images/Tooling/" + i + ".png";
            }
        }`

“1c.png”图像是选中的图像,应替换为“1.png”。此页面上有多个div可容纳多个图像,这些图像名为2 / 2c,3 / 3c,这就是包含var i的原因。任何见解?提前谢谢。

2 个答案:

答案 0 :(得分:1)

你可以这样做,它也允许不同的文件名。

var images = document.getElementsByClassName('selectable');

for (var image of images) {
  image.addEventListener('click', selectElementHandler);
}

function selectElementHandler(event) {
  var image = event.target,
      currentSrc  = image.getAttribute('src'),
      originalSrc = image.getAttribute('data-original-source'),
      selectedSrc = image.getAttribute('data-selected-source'),
      newSrc = currentSrc === originalSrc ? selectedSrc : originalSrc;

  image.setAttribute('src', newSrc);
}

// find all images with class "selectable"
var images = document.getElementsByClassName('selectable');

// add an event listener to each image that on click runs the "selectElementHandler" function
for (var image of images) {
  image.addEventListener('click', selectElementHandler);
}

// the handler receives the event from the listener
function selectElementHandler(event) {
  // the event contains lots of data, but we're only interested in which element was clicked (event.target)
  var image = event.target,
      currentSrc  = image.getAttribute('src'),
      originalSrc = image.getAttribute('data-original-source'),
      selectedSrc = image.getAttribute('data-selected-source'),
      // if the current src is the original one, set to selected
      // if not we assume the current src is the selected one
      // and we reset it to the original src
      newSrc = currentSrc === originalSrc ? selectedSrc : originalSrc;

  // actually set the new src for the image
  image.setAttribute('src', newSrc);
}

评论:

{{1}}

答案 1 :(得分:0)

您的问题是,javascript正在返回src的完整路径(您可以尝试alert(img.src);进行验证)。

如果您想要最强大的解决方案,您可以查找如何解析文件路径以获取javascript中的文件名。

但是,如果您确定所有图片都以&#39; c.png&#39;结尾,您可以使用最后5个字符的子字符串检查最后5个字符:

function changeImage(var i){
    var img = document.getElementById("imgCh" + i);

    if (img.src.substring(img.src.length - 5) === "c.png"){
        img.src = "images/Tooling/" + i + ".png";
    }
    else
    {
        img.src = "images/Tooling/" + i + "c.png";
    }
}