Jquery用名称替换href

时间:2013-07-08 21:49:57

标签: jquery replace

我在单个页面的主体中分散了26行,我需要通过文件的HEAD中的jquery进行更改。

<a href="A">A</a>
<a href="B">B</a>
<a href="C">C</a>
<a href="D">D</a>
<a href="E">E</a>
<a href="F">F</a>

我需要制作所有26个实例锚链接。所以我需要他们从'href'改为'name'。我没有权限直接更改正文内容,因此jquery。

http://jsfiddle.net/deekster/ufRxr/5/

(出于演示目的,我手动更正了第一项 - A.使'结果'窗口变小以便看到A锚点工作)。我感谢任何人的回复。

4 个答案:

答案 0 :(得分:3)

喜欢这个吗?

$('a[href]').attr('name', function () {
    var href = this.href;
    return href.substr(href.lastIndexOf('#') + 1);
}).removeAttr('href');

<强> Fiddle

或者

$('a[href]').attr('name', function () {
    var href = this.href;
    this.removeAttribute('href');
    return href.substr(href.lastIndexOf('#') + 1);
});

<强> Fiddle

另一个正则表达式示例:

$('ul a[href]').attr('name', function () {
    return this.href.match(/#([^#]*)$/)[1];
}).removeAttr('href');

<强> Fiddle

答案 1 :(得分:1)

这是一个例子:

// select all a element with an href attribute after a ul element
$('ul ~ a[href]').each(function(){
    // set the href attribute to name
   $(this).attr('name', $(this).attr('href'));
    // remove attribute href
   $(this).removeAttr('href');
});

请注意,我在ul之后仅更换了元素。也许你可以使用更好的选择。例如:div.content a[href]选择具有类内容的div中的所有锚点。

JsFiddle

答案 2 :(得分:0)

这应该这样做

http://jsfiddle.net/ufRxr/10/

$('li a').each(function(){
    $(this).attr('name', $(this).attr('href').replace('#', ''));
    $(this).removeAttr('href');
});

答案 3 :(得分:0)

我会使用看起来像这样的jQuery函数:

// for every a-tag that has an href attribute
$('a[href]').each(function() {
    // get the href attribute
    href = $(this).attr('href');
    // of the href does not start with '#'
    if (href.substr(0,1) != '#') { 
        // set the value form href to the name attribute
       $(this).attr('name', href);
        // remove the href attribute
       $(this).removeAttr('href');
    }
});

我已将解释放在评论中,但请随时询问您是否要我详细说明。

更新的小提琴:http://jsfiddle.net/ufRxr/8/

相关问题