jQuery replacing relative links

后端 未结 6 1259
忘掉有多难
忘掉有多难 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:46

    .prop() grabs the property value as opposed to the attribute value. While similar, there are some subtle, important differences -- one of which applies here. The href property on an element is always the full path. For example:

    <a id="myAnchor" href="/foo.html"></a>
    
    <script>
    elem = document.getElementById('myAnchor');
    $elem = $(elem);
    alert(elem.href); //alerts the full path, http://www.example.com/foo.html
    alert($elem.prop('href')); //same as above
    alert($elem.attr('href')); //alerts just "/foo.html"
    </script>
    

    In other words, you're appending the domain to a value that is already an absolute path. Just use .attr() rather than .prop() and you'll be fine.

    To see an example, open your console and go to this page: http://jsfiddle.net/JUcHU/

    0 讨论(0)
  • 2020-12-19 17:51

    The code:

    $(function() {
        $('input').click(function() {
            $('a').not('[href^="http"],[href^="https"],[href^="mailto:"],[href^="#"]').each(function() {
                $(this).attr('href', function(index, value) {
                    if (value.substr(0,1) !== "/") {
                        value = window.location.pathname + value;
                    }
                    return "http://mynewurl.com" + value;
                });
            });
        });
    });
    

    See this jsfiddle: http://jsfiddle.net/aknosis/kWrjr/

    Here's a link to my solution to this problem: http://aknosis.com/2011/07/17/using-jquery-to-rewrite-relative-urls-to-absolute-urls-revisited/

    0 讨论(0)
  • 2020-12-19 17:52

    try simply with

    $(document).ready(function() {
      $("a[href^='/']").each(function(){ 
        var cur_href = this.href;  /* <-- access to the href attribute 
                                          through the DOM reference */  
        $(this).prop("href", 'http://www.mysite.com'+cur_href);
      });
    });
    
    0 讨论(0)
  • 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 = $( '<a href="https://example.com/foo">bar</a>' )[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.
    0 讨论(0)
  • 2020-12-19 17:57

    Try something like this:

    if(! /http/.test( cur_href) ){
       $(this).attr("href", 'http://www.mysite.com'+cur_href);
    
    }
    
    0 讨论(0)
  • 2020-12-19 18:06

    This is not pretty, but it should work across browsers:

    $(document).ready(function() {
      $("a[href^='/']").each(function(){ 
        var cur_href = $(this).attr("href");
        if( cur_href.indexOf( "http" ) !== -1 ) {
            $(this).attr("href", cur_href);
        } else {
            $(this).attr("href", 'http://www.mysite.com'+cur_href);
        }  
      });
    });
    
    0 讨论(0)
提交回复
热议问题