I am trying to make a hyperlink on every url in my page. There is code like this:
<div id="divC">
Hello testing message
My profile link : http://stackoverflow.com/users/568085/abhishek and
my user account link :
<a href="http://stackoverflow.com/users/568085/abhishek">
<img height="58" width="208" title="Stack Overflow profile for Abhishek at Stack Overflow, Q&am开发者_如何学编程p;A for professional and enthusiast programmers" alt="Stack Overflow profile for Abhishek at Stack Overflow, Q&A for professional and enthusiast programmers" src="http://stackoverflow.com/users/flair/568085.png?theme=dark">
</a>
</div>
and I used below javascript function to add link on every URL in content page :
<script>
//call function for linking every url
createLinks();
function createLinks()
{
var exp=/(((\b(https?|ftp|file):\/\/))[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
$("div#divC").each(function(index) {
$(this).html($(this).html().replace(exp, "<a target='_self' class='msg_links' href=$1>$1</a>"));
});
}
</script>
In above code working fine but I don't want to create link on <img src='www.test.com'>
.
when I run this it also created link in the <img src="<a href='www.test.com'>www.test.com</a>" >
,
<img>
src.?Ah... I see what you are doing. I've did it a while ago, building a plugin that replaces smiley's :D. Does this code work better?
//call function for linking every url
createLinks();
function createLinks()
{
var exp=/(((\b(https?|ftp|file):\/\/))[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
$("div#divC")
.contents()
.filter(function () {
if (typeof (Node) == 'undefined') {
return this.nodeType == 3;
}
else {
return this.nodeType == Node.TEXT_NODE;
}
}).each(function(index) {
var x = $(this)[0].nodeValue;
if (x != '') {
x = x.replace(exp, "<a target='_self' class='msg_links' href='$1'>$1</a>");
$(this).replaceWith(x);
}
});
}
Put an id to you tag and match it with your jquery
1. <a id="target" href="your/target/url">
2. ${"#target"}.attr('href','new/target/url')
It is because you are using .each(). If you want to change multiple use a class attribute for your tags.
精彩评论