javascript - 使用图像 jquery 切换

标签 javascript jquery html

当单击 add_hide_calculator 时,我希望图像变为 calculator_open-img,再次单击时,我希望图像变回原样。这是我目前所拥有的,我无法在点击时更改图片:

Jquery.js

$('#add_hide_calculator').on("click", function() {
    var text = $(this).val();
    $("#calculator").toggle();
});

$(window).on("click keydown", function(e) {
  //e.preventDefault()
  //sets the esc key button 
  if (e.keyCode === 27 || !$(e.target).is(function() {return $("#calculator, #add_hide_calculator")})) {
    $("#calculator").hide()
  }
}).focus()

/* toggling image starts here */

$('#add_hide_calculator').on("click", function() {
    var text = $(this).text();

    if (text == "<img src='calculator_open-img.png' width='200px' height='190px'>") {
      $(this).html("<img src='calculator_close-img.png' width='200px' height='190px'>");
    } else {
      $(this).html("<img src='calculator_open-img.png' width='200px' height='190px'>");
    }
});

索引.php

<a id="add_hide_calculator"><img src="calculator_close-img.png" width="200px" height="190px"></a>

最佳答案

您可以检查 src 属性值

$('#add_hide_calculator').on("click", function() {

  $(this).find('img').attr('src', function(i, src) {
    return src == "calculator_open-img.png" ? "calculator_close-img.png" : "calculator_open-img.png";
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<a id="add_hide_calculator">
  <img src="calculator_close-img.png" width="200px" height="190px">
</a>

关于javascript - 使用图像 jquery 切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35356605/

相关文章:

javascript - 在路径上绘制 SVG 图像,但大小根据需要而定

Jquery ASP.NET 2.0

javascript - 如何获取 div 内标签内的单选按钮?

javascript - jquery 头文件冲突

html - 调整浏览器大小时坡度保持流动(使用剪辑路径)

javascript - 在 while 循环中调用函数并赋值。骰子作业问题

javascript - 与 Javascript 中的 If else 语句比较问题

html - 仅使用 css 翻转/反转/镜像文本

javascript - Facebook - javascript 登录

添加 doctype 后 JavaScript 被破坏