简体   繁体   English

如何创建一个辅助函数来使用jQuery更改图像?

[英]How can I create a helper function to change image using jQuery?

I tried to create an imgLoader function that take in 3 arguements : 我试图创建一个包含 3个论点的imgLoader函数:

  • btn : the btn that got click btn:获得点击的btn
  • img : the specific img that will be load on img:将在其上加载的特定img
  • imgPath : the path to the img that I want to load imgPath:我要加载的img的路径

I also want the btn to be optional, so I check if btn is true. 我也希望btn是可选的,因此我检查btn是否为true。

Here is what I come up with : 这是我想出的:

function imgLoader( btn, img, imgPath) {

    if (btn) {
        $btnBiDefault.removeClass('btn-bi-default-clicked');
        btn.addClass('btn-bi-default-clicked');
    }

    img.attr('src', imgPath);

}

I tried to call imgLoader in one of my click funtion : 我试图在我的点击功能之一中调用imgLoader

$name.click(function(e) {
    e.preventDefault();

    imgLoader({
        img: $img,
        imgPath: '/path-to-img/image.png'
    });
});

I got 0 error, not even warning on my .js file. 我得到0错误,甚至没有警告我的.js文件。 I couldn't get my img to load. 我无法加载我的img。

I keep getting : 我不断得到:

Uncaught TypeError: btn.addClass is not a function 未捕获的TypeError:btn.addClass不是函数

Can someone please give me a hint ? 有人可以给我提示吗?

You should probably pass an object instead of three separate variables. 您可能应该传递一个对象而不是三个单独的变量。 This allows you to have greater control of what you're able to send to the function. 这使您可以更好地控制要发送给该功能的内容。 For example, you could call your imgLoader function with no button: imgLoader({img: "...", imgPath: "..."}) or with a button: imgLoader({btn: $(ele), img: "...", imgPath: "..."}) . 例如,您可以不使用任何按钮调用imgLoader函数: imgLoader({img: "...", imgPath: "..."})或使用按钮: imgLoader({btn: $(ele), img: "...", imgPath: "..."})

The order of the elements within the object you're passing is irrelevant, and can be called using dot notation: args.item . 您要传递的对象中元素的顺序无关紧要,可以使用点表示法args.item进行调用。

Try something like this: 尝试这样的事情:

 function imgLoader(args) { "use strict"; if (typeof args.btn !== "undefined") { // Do things with your button here. } $(args.img).attr('src', args.imgPath); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button type="button" onClick="imgLoader({btn: this, img: '#imgID', imgPath: 'http://lorempixel.com/400/200/cats'})">Get a cat</button> <img id="imgID" alt="A random cat." /> 

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

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