简体   繁体   English

切换图像jQuery

[英]toggling with image jquery

when clicked on add_hide_calculator I would like the image to change in to calculator_open-img , and when clicked again, I would like the image to change back. 单击add_hide_calculator我希望将图像更改为add_hide_calculator calculator_open-img ,再次单击时,我希望将图像更改回。 This is what I have so far I am unable to change the picture on click: 到目前为止,这是我无法更改的图片:

Jquery.js 的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'>");
    }
});

Index.php 的index.php

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

change this line 改变这条线

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

to

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

you basically are comparing the html inside the anchor (link) not the text. 您基本上是比较锚点(链接)内的html而不是文本。 Text is what you finally see after html is rendered. 文本是您在呈现html之后最终看到的内容。

You can check for the src attribute value 您可以检查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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM