简体   繁体   中英

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

currently I am using fancybox to display iframes like this:

$('#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 . 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):

$('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 .

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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