find and replace <a> tags in Javascript or PHP
I am trying to get links to execute javascript instead of the href attribute. I've scoured the web and can get close with several different methods, but no cigar.
Example conversions look like this:
<a href="http://example.com">Link 1</a>
<a href="http://www.yahoo.com" target="_blank" class="whatever">Link 2</a>
to something like:
<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>
Examples of what I've tried:
- The content is dynamic so I tried replacing on the fly with JQuery, but it still executes the href AND the 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; });
-I've also tried replace the links BEFORE the content is written to the page
$(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>");
});
-And lastly I tried to Linkify() but this only works for text urls, and leaves tags a mess:
functi开发者_运维问答on 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'); }
Does anyone have any suggestions in either Javascript/JQuery (or as a backfall PHP)? For something so seemingly simple, I just haven't been able to figure it out...
Much thanks in advace
$('a').each(function() {
$(this).click(function() { OpenLink($(this).attr('href')); return false; });
$(this).attr('href', '#');
});
What about:
$("a").attr("href", "#").click(/* handler */);
EDIT: if you want to remove all attributes, implement this solution: Remove all attributes
Try looking here:
Proper way for links to execute javascript code
It would be better to do
$('a').click(function (e) {
OpenLink($(this).attr('href'); e.preventDefault() });
That way you would still have the original href accessible and wouldn't have to actually modify the DOM, and some people discourage returning false from an event handler to block a link.
精彩评论