[英]find and replace <a> tags in Javascript or PHP
我正在嘗試獲取執行 javascript 而不是 href 屬性的鏈接。 我已經搜索了 web 並且可以通過幾種不同的方法接近,但沒有雪茄。
示例轉換如下所示:
<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>
我試過的例子:
$("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() 但這僅適用於文本 url,並且讓標簽一團糟:
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)有任何建議嗎? 對於看似簡單的事情,我一直無法弄清楚......
非常感謝提前
$('a').click(function (e) {
OpenLink($(this).attr('href'); e.preventDefault() });
這樣,您仍然可以訪問原始的 href,並且不必實際修改 DOM,並且有些人不鼓勵從事件處理程序返回 false 來阻止鏈接。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.