使用图像 jQuery 切换

toggling with image jquery

本文关键字:切换 jQuery 图像      更新时间:2023-09-26

当点击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>

更改此行

var text = $(this).text();

var text = $(this).html();

您基本上是在比较锚点(链接)内的 HTML,而不是文本。文本是呈现 html 后最终看到的内容。