简体   繁体   中英

jquery modify href extension onclick

I'm trying to keep my application working even if the user doesn't have js, and I noticed my lightbox wasn't working with ajax goodness on an old brower and went about trying to fix it but wasn't sure how to get around this.

I have a link with a class

<a href="/blah/1234", class="modal">Blah</a>

but I need to tell the lightbox to use the href + .js extension if it works. That way if the user has no js or it breaks for any reason it'll send them to the fallback page and behave normally.

    $('.modal').lightbox({
            'width'       : 465,
            'height'      : 375,
            'autoresize'  : false,
            'modal'       : true
    });

The lightbox had no href attribute I could find to change it with it's own param so I tried to do it before hand but a bit too messy.

This works badly, but breaks after they click it once as it adds .js everytime.

$('.modal').bind('click', function() {
    $('.modal').attr("href", $('.modal').attr("href") + '.js');
    $('.modal').lightbox({
            'width'       : 465,
            'height'      : 375,
            'autoresize'  : false,
            'modal'       : true
    });
});

How can I change the extension more simply just before calling the lightbox?

You can use a function with .attr() to check if it already ends in .js , like this:

$('.modal').attr("href", function(i, href) {
  return href + (href.slice(-3) == '.js' ? '' : '.js');
});

Or, do it to all the links on ready , like this:

$('.modal').attr('href', function(i, href) {
  return href + '.js';
}).lightbox({
  'width'       : 465,
  'height'      : 375,
  'autoresize'  : false,
  'modal'       : true
});

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