通过jQuery设置锚href与本机dom元素

通过jQuery设置锚href与本机dom元素

本文介绍了通过jQuery设置锚href与本机dom元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从以下两个答案中

From two of the answers to this question I came up with a question of my own.

给予

 <a href="#example">

使用jQuery将教学锚点更改为

use jQuery to change teach anchor to

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

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

There were two nearly identical answers given:

$('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"属性的对象则没有得到预期的结果. (小提琴)

The one that wraps the native dom element to a jQuery object gives the expected result, whereas the one that uses the ".href" property does not. (Fiddle)

.href在那里发生了什么事?

What's going on with .href there?

推荐答案

element.href返回元素的href属性,这是一个绝对URL,而attr('href')返回该属性中的所有内容,这就是区别. /p>

element.href returns the href property of the element, which is an absolute URL, while attr('href') returns whatever is in the attribute, that's the difference.

<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

这篇关于通过jQuery设置锚href与本机dom元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 05:20