简体   繁体   中英

jquery attr() value isn't being replaced?

First time posting on here, looked through a couple of possible similar titles, still nothing.. :(

Trying to get up to date with jQuery/javascript. Well, my problem is that I would like to change my anchor element's href attribute value depending if the doc width is below 1022px. I've been able to successfully alert the href value, but where I have my commented ALERT (which works) the href string is not updated... Not sure why, any help would be greatly appreciated.

if(document.width < 1022)
{
    var allLinks = $('.filtered_portfolio li a');
    allLinks.each(function(){
        var thisLink = $(this);
        anchorLinkUrl = this
        alert (anchorLinkUrl);

        if( anchorLinkUrl.indexOf('[iframe]=true&lightbox[width]=800&lightbox[height]=540') != -1){
            anchorLinkUrl.replace('[iframe]=true&lightbox[width]=800&lightbox[height]=540','donkey');
            //alert('hi');
        }
    });
}    

Your anchorLinkUrl variable is assigned the DOM element, not just the href value. To update the href of the link, try this (untested):

if(document.width < 1022)
        {
            $('.filtered_portfolio li a').each(function(){
                this.href = this.href.replace('[iframe]=true&lightbox[width]=800&lightbox[height]=540','donkey');
                });
        }

Here is an example of how you can use jQuery's .attr() function to get/set an attribute of a selected element, hope this helps.

$('a').toggle(function(e) {
    e.preventDefault();
    // setting an attribute
    $(this).attr('href', 'www.yahoo.com');
},function(e) {
    e.preventDefault();
    // setting an attribute 
    $(this).attr('href', 'www.google.com');
}).click(function(e) {
    e.preventDefault();
    // getting an attribute
    $('#foo').text($(this).attr('href'));
});

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