jQuery replacing relative links

后端 未结 6 1271
忘掉有多难
忘掉有多难 2020-12-19 17:33

Hopefully someone can explain some odd behavior I\'ve encountered with jQuery. The following script is looking for relative links on my page and replacing them with absolut

6条回答
  •  醉酒成梦
    2020-12-19 17:54

    jQuery isn't causing a problem here. The issue is that the href property of HTMLAnchorElement (the type of object jQuery is returning), per the spec, always contains an absolute URI.

    In HTML5 href is a composite attribute and you can just swap the protocol (the part before //) at will by modifying href.protocol, e.g.:

    var link = $( 'bar' )[0];
    console.log( link.href );
    // => https://example.com/foo
    
    link.href.protocol = 'http:';
    console.log( link.href );
    // => http://example.com/foo
    

    For older browsers without the composite href you'll just have to make do with a regex:

    console.log( link.href );
    // => https://example.com/foo
    
    link.href = link.href.replace( /^https:/, 'http:' );
    console.log( link.href );
    // => http://example.com/foo
    

    TLDR: Your code should look something like this:

    $( "a[href^='/']" ).prop( "href",
      function( _idx, oldHref ) {
        return oldHref.replace( /^https:/, 'http:' );
      }
    );
    

    P.S. You'll notice that I elided your $.each call. That's because prop automatically acts on every element in the matched set, i.e. it already does what you were doing with each.


    .prop( propertyName, function(index, oldPropertyValue) )

    • propertyName The name of the property to set.
    • function(index, oldPropertyValue) A function returning the value to set. Receives the index position of the element in the set and the old property value as arguments. Within the function, the keyword this refers to the current element.

提交回复
热议问题