我正在尝试在页面中的每个网址上创建超链接。 有这样的代码:
<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&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>
我使用下面的javascript函数在内容页面的每个URL上添加链接:
<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>
上面的代码工作正常,但我不想在 <img src='www.test.com'>
上创建链接。
当我运行它时,它还在 <img src="<a href='www.test.com'>www.test.com</a>" >
中创建了链接,如何避免在 <img>
src中创建链接。?< / p>
答案 0 :(得分:1)
//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);
}
});
}
答案 1 :(得分:0)
将id添加到您的标记并将其与您的jquery匹配
1. <a id="target" href="your/target/url">
2. ${"#target"}.attr('href','new/target/url')
这是因为你正在使用.each()。如果要更改多个,请使用标记的类属性。