简体   繁体   English

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

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

currently I am using fancybox to display iframes like this: 目前,我正在使用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
    });
});

However doing this is tedious and requires copying the same code over and over. 但是,这样做很麻烦,并且需要一遍又一遍地复制相同的代码。 Is there an alternative that would allow to use a single function? 是否有允许使用单个功能的替代方法? Such an operation would take whatever is #img-ID and change href to doc-ID.html . 这样的操作将采用#img-ID任何内容,并将href更改为doc-ID.html Or, alternatively, how to do this using a class (each element still needs a specific link)? 或者,或者,如何使用一个类来做到这一点(每个元素仍然需要一个特定的链接)?

Is this possible? 这可能吗?

The simplest solution here is 这里最简单的解决方案是

$('[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
    });
});

This is what I came up with a few minutes after posting ( mask is a class that all elements share): 这是我在发布后几分钟想到的( mask是所有元素共享的类):

$('div.mask').click(function() {

    var id = $(this).attr('id');
    var documentLink = "work-" + id.split("-")[1] + ".html";

    $.fancybox({
        type: 'iframe',
        href: documentLink,
        showCloseButton: true
    })
}
);

However I'm wondering if there are better ways to handle documentLink . 但是我想知道是否有更好的方法来处理documentLink

This shall guide you: 这将指导您:

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

and apply to all images or whatever selector you wish: 并应用于所有图像或所需的任何选择器:

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

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

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