jQuery:对于类似的操作,使用单个函数而不是重复的函数

jQuery: use a single function instead of repeated functions for similar operations

本文关键字:函数 单个 于类似 操作 jQuery      更新时间:2023-09-26

目前我使用的是fancybox来显示iframe:

$('#img-001').click(function() {
    $.fancybox({
        type: 'iframe',
        href: 'doc-001.html',
       showCloseButton: true
    });
});

$('#img-002').click(function() {
    $.fancybox({
        type: 'iframe',
        href: 'doc-002.html',
        showCloseButton: true
    });
});

然而,这样做是乏味的,需要一遍又一遍地复制相同的代码。是否存在允许使用单个函数的替代方法?这样的操作将取#img-ID,将href变为doc-ID.html。或者,如何使用类(每个元素仍然需要一个特定的链接)来做到这一点?

这可能吗?

这里最简单的解决方法是

$('[id^="img-"]').click(function() { // select all elements whose id starts with "img-"
    $.fancybox({
        type: 'iframe',
        href: 'doc'+this.id.slice(3)+'.html', // takes the "-007" part of "img-007"
        showCloseButton: true
    });
});
$('#img-001, #img-002').click(function() {
    var code = this.id.replace('img', '');
    $.fancybox({
        type: 'iframe',
        href: 'doc' + code + '.html',
        showCloseButton: true
    });
});
$('#img-001,#img-002').click(function() {
    $.fancybox({
        type: 'iframe',
        href: 'doc-'+this.id.split['-'][1]+'.html',
       showCloseButton: true
    });
});

这是我在发布后几分钟想到的(mask是所有元素共享的类):

$('div.mask').click(function() {
    var id = $(this).attr('id');
    var documentLink = "work-" + id.split("-")[1] + ".html";
    $.fancybox({
        type: 'iframe',
        href: documentLink,
        showCloseButton: true
    })
}
);

然而,我想知道是否有更好的方法来处理documentLink

这将指导你:

function magic(){
    m = $(this).attr("id").match(/.*-(.*)/)
    $.fancybox({
       type: 'iframe',
       href: 'doc-'+m[1]+'.html',
       showCloseButton: true
     });
}

并应用于所有图像或任何你想要的选择器:

$("body").find("img").each(magic);