gpt4 book ai didi

javascript - 从 .click() 中调用 jQuery 函数

转载 作者:行者123 更新时间:2023-11-28 17:46:54 24 4
gpt4 key购买 nike

我不确定为什么这段代码不起作用。目标是当用户点击 .accent 时隐藏一张图像并在其位置显示另一张图像。当前显示的图像(在页面加载时显示)由 .ssi-hide 类引用。

这是 jQuery:

    jQuery(document).ready(function($){
// jQuery methods go here...

var currentImage = '".ssi-hide"';

$(".accent").click(function() {
swapImage( currentImage, "#accent-img" );
});
}); //end jQuery

这是函数:

    (function( $ ) {
$.fn.swapImage = function( outPic, inPic ) {
$( outPic ).fadeOut(200, function(){
$( inPic ).fadeIn(400).css("display", "block").css("margin", "auto");
});
currentImage = inPic;
};
})( jQuery );

Chrome 通知:“Uncaught ReferenceError:swapImage 未定义”以及“未捕获错误:语法错误,无法识别的表达式:“.ssi-hide””

非常感谢您的帮助。

最佳答案

首先,currentImage 不需要两组引号,请使用 var currentImage = ".ssi-hide"; 代替。

您调用该函数就好像它是一个作用域函数,但它是一个 jQuery 插件。而不是:

$(".accent").click(function() {
swapImage( currentImage, "#accent-img" );
});

应该是:

$(".accent").click(function() {
$(this).swapImage( currentImage, "#accent-img" );
});

但我不明白为什么你需要将它作为 jQuery 插件,因为它在任何地方都不使用 this

相反,它实际上应该被定义为类函数

(function( $ ) {
$.swapImage = function( outPic, inPic ) {
$( outPic ).fadeOut(200, function(){
$( inPic ).fadeIn(400).css("display", "block").css("margin", "auto");
});
currentImage = inPic;
};
})( jQuery );

然后你打电话

$(".accent").click(function() {
$.swapImage( currentImage, "#accent-img" );
});

关于javascript - 从 .click() 中调用 jQuery 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46477264/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com