如何从AJAX响应中删除所有href

时间:2013-05-28 17:44:30

标签: jquery ajax response href removeall

我正在导入一个HTML文件,我想从其上的所有元素中删除所有href,因此最终文本不会链接到任何地方,并且显示为“普通”文本。

我已经从这个HTML中只获取了一部分div#divvy,因此删除href的过程必须适用于此而不是所有响应。

最终结果应转到div#pepeland

我有这段代码:

function pepe(){
    $.ajax({
        url: 'http://www.site.com/text.html',
        dataType: 'html',
        success: function(response){
            $('#pepeland').html(jQuery(response).find('#divvy').html());
        }
    });
};

我想但是我不确定我是否应该在上面的代码中插入类似以下行之一的东西,但我不知道该怎么做。

$(response).querySelectorAll("href").remove();

$(response).attr('href', '');

response.replace("href", '');

在下面的答案,我意识到我想要的是删除所有标签而不删除文本。因为单词保持格式化下划线和标签的所有属性。所以烤了为我写的正确答案,见下文!

3 个答案:

答案 0 :(得分:1)

我需要查看你的html文件,看看如何选择元素,但你需要循环遍历所有元素才能全部替换它们。所以像这样......

$('YOUR SELECTOR').each(function(){
      $(this).contents().unwrap();
});

这会将锚标记移开并使其成为纯文本。

类似于这个问题的答案.. Remove a HTML tag but keep the innerHtml

答案 1 :(得分:0)

试试这个:

function pepe(){
    $.ajax({
        url: 'http://www.site.com/text.html',
        dataType: 'html',
        success: function(response){
            var $divvy = $(response).find('#divvy');
            $divvy.find('a').each(function(){$(this).replaceWith($(this).text())});
            $('#pepeland').html($divvy);
        }
    });
};

答案 2 :(得分:0)

我会做这样的事情:

$.ajax({
    url: 'http://www.site.com/text.html',
    dataType: 'html',
    success: function(response){
        $('#pepeland').html(response);
        $('#pepeland a').removeAttr('href');
    }
});

这会删除附加的html

中所有链接的href属性