我在使用Jquery更改点击事件上的图像时遇到问题

时间:2022-11-09 22:27:50

I am trying to swap image when an image is clicked...here is my jquery so far and it's not working.

我试图在点击图像时交换图像...到目前为止这是我的jquery并且它不起作用。

$(document).ready(function(){
imgFldr = '../../App_Themes/Default/Images/';
    $('#smallImg1').click(function(){

        $('#smallImg1').attr('src', imgFlder+'belkinSmall4.png');
    });
});

And below is an example of my HTML

以下是我的HTML示例

<div>
     <img id="smallImg1" src="../../App_Themes/Default/Images/belkinSmall1.png" />
</div>

Any help would be appreciated!

任何帮助,将不胜感激!

1 个解决方案

#1


I would have written it like this:

我会这样写的:

$(function() {
  var imageFolder = '../../App_Themes/Default/Images/';
  $('#smallImg1').click(function(){
    $(this).attr('src', imageFolder + "belkinSmall4.png");
  });
});
  • $(function() { ... }) is shorthand for $(document).ready(function() { ... })
  • $(function(){...})是$(document).ready(function(){...})的简写

  • imageFolder instead of imgFldr. Pointless abbreviation imo.
  • imageFolder而不是imgFldr。无意义的缩写imo。

  • var imageFolder, too (var is the key here), so that it is a local variable, not a global.
  • var imageFolder也是(var是这里的关键),因此它是一个局部变量,而不是全局变量。

  • $(this) instead of $('#smallImg1'), to avoid duplications. The result is identical.
  • $(this)而不是$('#smallImg1'),以避免重复。结果是一样的。

However, this is just a re-factoring of your code — both your snippet and mine should work.

但是,这只是对代码进行重新分解 - 您的代码段和我的代码都应该正常工作。

So, "doesn't work" - does the image change? Is the path invalid? Do you get any JS runtime errors? What if you set the src to '../../App_Themes/Default/Images/belkinSmall4.png' by hand — does the image exist?

所以,“不起作用” - 图像是否会改变?路径无效吗?你有任何JS运行时错误吗?如果您手动将src设置为'../../App_Themes/Default/Images/belkinSmall4.png',该图像是否存在?

#1


I would have written it like this:

我会这样写的:

$(function() {
  var imageFolder = '../../App_Themes/Default/Images/';
  $('#smallImg1').click(function(){
    $(this).attr('src', imageFolder + "belkinSmall4.png");
  });
});
  • $(function() { ... }) is shorthand for $(document).ready(function() { ... })
  • $(function(){...})是$(document).ready(function(){...})的简写

  • imageFolder instead of imgFldr. Pointless abbreviation imo.
  • imageFolder而不是imgFldr。无意义的缩写imo。

  • var imageFolder, too (var is the key here), so that it is a local variable, not a global.
  • var imageFolder也是(var是这里的关键),因此它是一个局部变量,而不是全局变量。

  • $(this) instead of $('#smallImg1'), to avoid duplications. The result is identical.
  • $(this)而不是$('#smallImg1'),以避免重复。结果是一样的。

However, this is just a re-factoring of your code — both your snippet and mine should work.

但是,这只是对代码进行重新分解 - 您的代码段和我的代码都应该正常工作。

So, "doesn't work" - does the image change? Is the path invalid? Do you get any JS runtime errors? What if you set the src to '../../App_Themes/Default/Images/belkinSmall4.png' by hand — does the image exist?

所以,“不起作用” - 图像是否会改变?路径无效吗?你有任何JS运行时错误吗?如果您手动将src设置为'../../App_Themes/Default/Images/belkinSmall4.png',该图像是否存在?