javascript 如何禁用锚(链接)标签(转换为跨度)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6639650/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 21:21:59  来源:igfitidea点击:

How to disable an anchor (link) tag (convert to span)

javascriptjquerydom

提问by Peter Lyons

I have a bunch of anchor tags (<a>) that I need to convert to <span>tags. I don't need to do this to disable clicking (I know about preventDefault()and returning falsefrom the click event handler). I just need to do this to enable drag and drop sorting (which IE forbids on an anchor tag but permits on a span).

我有一堆锚标签 ( <a>),我需要将它们转换为<span>标签。我不需要这样做来禁用点击(我知道preventDefault()false从点击事件处理程序返回)。我只需要执行此操作即可启用拖放排序(IE 禁止对锚标记进行排序,但在跨度上允许)。

I have a working solution that is fine.

我有一个很好的工作解决方案。

http://jsfiddle.net/5HGbx/

http://jsfiddle.net/5HGbx/

I'm just wondering if any of you wizards have a slicker way of achieving the same end result.

我只是想知道你们中的任何一个巫师是否有达到相同最终结果的更巧妙的方法。

回答by naveen

you could use replaceWithfrom jQuery API

你可以replaceWith从 jQuery API 使用

$('#myButton').click(function(){
    $("#someDiv a").replaceWith(function(){
        return $("<span>" + $(this).html() + "</span>");
    });
});

Fiddle here: http://jsfiddle.net/naveen/ufYCt/1/

在这里小提琴:http: //jsfiddle.net/naveen/ufYCt/1/

回答by mu is too short

Mixing standard DOM methods with jQuery is a bit odd and unnecessary. You could just do something like this instead:

将标准 DOM 方法与 jQuery 混合使用有点奇怪和不必要。你可以这样做:

function aToSpan() {
    var $link = $('a');
    var $span = $('<span>');
    $link.after($span.html($link.html())).remove();
}

This just copies the link's content to a new <span>and then replaces the <a>with the new <span>.

这只是将链接的内容复制到一个新的<span>,然后用<a>新的<span>.

References:

参考:

回答by Kaisar

from the naveen's answer you will lose the hreftag

从 naveen 的回答中,您将丢失href标签

if you want href tag too just modify this as follows...

如果你也想要 href 标签,只需修改如下...

$('#myButton').click(function(){
    $("#someDiv a").replaceWith(function(){
        return $("<span href=\""+$(this).attr('href')+"\">" + $(this).html() + "</span>");
    });
});