通过jquery与native dom元素设置anchor href

时间:2014-03-14 20:46:38

标签: javascript jquery html

this问题的两个答案中,我提出了一个我自己的问题。

鉴于

 <a href="#example">

使用jQuery将教学锚更改为

<a href="//example.com/page#example>

给出了两个几乎相同的答案:

$('a[href^="#"]').each(function(index, element){
    var $ele = $(element),
        oldHref = $ele.attr('href');
    $ele.attr('href', '//example.com/page'+ oldHref);
});

$('a[href^="#"]').each(function(i,el){
    el.href = "http://www.example.com/pageslug" + el.href;
});

将本机dom元素包装到jQuery对象的那个给出了预期的结果,而使用“.href”属性的那个没有。 (Fiddle

.href在那里发生了什么?

1 个答案:

答案 0 :(得分:1)

element.href返回元素的href属性,这是一个绝对URL,而attr('href')返回属性中的任何内容,这就是差异。

<a href="#test"></a>

-

element.href         // returns absolute URL, as in http://stackoverflow.com#test
$(element).prop('href') // jQuery version of the above, returns absolute URL

element.getAttribute('href') // returns the attributes value, as in #test
$(element).attr('href')      // jQuery version of getAttribute, returns #test