查找并替换<a> tags in Javascript or PHP</a>

时间:2011-07-08 12:37:14

标签: php javascript jquery regex hyperlink

我正在尝试获取执行javascript而不是href属性的链接。我已经在网上搜索过,可以用几种不同的方法接近,但没有雪茄。

示例转换如下所示:

<a href="http://example.com">Link 1</a>
<a href="http://www.yahoo.com" target="_blank" class="whatever">Link 2</a>

类似于:

<a href="#" onclick="OpenLink('http://example.com');return false;">Link 1</a>
<a href="#" onclick="OpenLink('http://www.yahoo.com');return false;">Link 2</a>

我尝试过的例子:

  • 内容是动态的,所以我尝试用JQuery动态替换,但它仍然执行href和Javascript。
    $("a[href*=.com]").live('click', function(event){
    event.preventDefault();
    var href=this.href;
    // Modifications of the Attributes don't work here to disable/change href
    openMe(href);
    return false;
    });

- 我还尝试在将内容写入页面之前替换链接

$(input_content).find('a[href*=.com]').each(function(){
   var href = this.href;
   $(this).attr('href', 'javascript:openMe('+href+');');
   // AND
   $(this).closest('a').replaceWith("<a href='javascript:openMe("+href+");'>"+$(this).text()+"</a>");
});

- 最后我尝试了Linkify(),但这只适用于文本网址,并且标签一团糟:

function Linkify(inputText) {
    var replaceText, replacePattern1, replacePattern2, replacePattern3;
    //URLs starting with http://, https://
    replacePattern1 = /(\b(https?):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|">])/gim;
    replacedText = inputText.replace(replacePattern1, '$1');
}

有没有人在Javascript / JQuery(或作为支持PHP)中有任何建议?对于看似简单的事情,我一直无法弄清楚......

非常感谢advace

4 个答案:

答案 0 :(得分:4)

怎么样:

$("a").attr("href", "#").click(/* handler */);

修改 如果要删除所有属性,请实施此解决方案:Remove all attributes

答案 1 :(得分:4)

$('a').each(function() {

  $(this).click(function() { OpenLink($(this).attr('href')); return false; });
  $(this).attr('href', '#');
});

答案 2 :(得分:0)

答案 3 :(得分:0)

最好做

$('a').click(function (e) {
    OpenLink($(this).attr('href'); e.preventDefault() });

这样你仍然可以访问原始的href,并且不必实际修改DOM,并且some people discourage从事件处理程序返回false以阻止链接。