gpt4 book ai didi

javascript - 多次重复jquery函数

转载 作者:行者123 更新时间:2023-11-30 07:14:51 25 4
gpt4 key购买 nike

我需要改进我的 jquery 代码,我重复我的函数 6 次!!!有没有做一个循环来缩短代码?

(function( jQuery ){
jQuery.fn.vesta = function(imgN){
var imgPath = "http://localhost:8080/mhost/media/magentohost/vesta/vesta"
var currImg = imgPath + imgN + ".png";
var targetImg = jQuery('.img-browser img');
jQuery('.img-browser img').attr('src', currImg);
}
})( jQuery );

jQuery('.vesta1').on('click', function (e) {
jQuery('.vesta1').vesta(1);
});
jQuery('.vesta2').on('click', function (e) {
jQuery('.vesta2').vesta(2);
});
jQuery('.vesta3').on('click', function (e) {
jQuery('.vesta3').vesta(3);
});
jQuery('.vesta4').on('click', function (e) {
jQuery('.vesta4').vesta(4);
});
jQuery('.vesta5').on('click', function (e) {
jQuery('.vesta5').vesta(5);
});
jQuery('.vesta6').on('click', function (e) {
jQuery('.vesta6').vesta(6);
});

最佳答案

您可以通过使用一个公共(public)类和一个 data 属性来指定要发送到您的 vesta 函数的参数来干掉它:

<div class="vesta" data-vesta="1">1</div>
<div class="vesta" data-vesta="2">2</div>
<div class="vesta" data-vesta="3">2</div>

那么就根本不需要循环了:

$('.vesta').on('click', function (e) {
$(this).vesta($(this).data('vesta'));
});

关于javascript - 多次重复jquery函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28150760/

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