如何使用javascript遍历div中的所有外部链接,添加(或附加)类和alt-text?
我猜我需要获取div元素中的所有对象,然后检查每个对象是否都是a,并检查href属性是否以http(s)://开头(然后应该是一个外部链接),然后将内容添加到alt和class属性(如果它们不存在,则创建它们;如果它们存在,则附加所需的值)。
但是,我如何在代码中做到这一点呢?
发布于 2008-11-14 17:45:59
这个是测试过的:
<style type="text/css">
.AddedClass
{
background-color: #88FF99;
}
</style>
<script type="text/javascript">
window.onload = function ()
{
var re = /^(https?:\/\/[^\/]+).*$/;
var currentHref = window.location.href.replace(re, '$1');
var reLocal = new RegExp('^' + currentHref.replace(/\./, '\\.'));
var linksDiv = document.getElementById("Links");
if (linksDiv == null) return;
var links = linksDiv.getElementsByTagName("a");
for (var i = 0; i < links.length; i++)
{
var href = links[i].href;
if (href == '' || reLocal.test(href) || !/^http/.test(href))
continue;
if (links[i].className != undefined)
{
links[i].className += ' AddedClass';
}
else
{
links[i].className = 'AddedClass';
}
if (links[i].title != undefined && links[i].title != '')
{
links[i].title += ' (outside link)';
}
else
{
links[i].title = 'Outside link';
}
}
}
</script>
<div id="Links">
<a name="_Links"></a>
<a href="/foo.asp">FOO</a>
<a href="ftp://FTP.org/FILE.zip">FILE</a>
<a href="http://example.com/somewhere.html">SomeWhere</a>
<a href="http://example.com/somewhere2.html" class="Gah">SomeWhere 2</a>
<a href="http://example.com/somewhere3.html" title="It goes somewhere">SomeWhere 3</a>
<a href="https://another-example.com/elsewhere.php?foo=bar">ElseWhere 1</a>
<a href="https://another-example.com/elsewhere.php?foo=boz" class="Doh">ElseWhere 2</a>
<a href="https://another-example.com/elsewhere.php?foo=rad" title="It goes elsewhere">ElseWhere 3</a>
<a href="deep/below/bar.asp">BAR</a>
<a href="javascript:ShowHideElement('me');">Show/Hide</a>
</div>如果您使用的是共享服务器上的帐户,例如http://big-server.com/~UserName/,您可能希望将URL硬编码为超出顶层。另一方面,如果您希望将http://foo.my-server.com和http://bar.my-server.com标记为本地,则可能需要更改RE。
在良好的评论之后更新改进的健壮性...
我不会强调FTP或其他协议,它们可能需要一个不同的例程。
发布于 2008-11-14 15:48:15
我认为像这样的东西可以作为一个起点:
var links = document.getElementsByTagName("a"); //use div object here instead of document
for (var i=0; i<links.length; i++)
{
if (links[i].href.substring(0, 5) == 'https')
{
links[i].setAttribute('title', 'abc');
links[i].setAttribute('class', 'abc');
links[i].setAttribute('className', 'abc');
}
}您还可以遍历文档中的所有A元素,并检查父级以查看div是否就是您要查找的div
发布于 2008-11-14 15:36:42
使用Jquery可以很容易地实现这一点。您可以将以下代码添加到onload中:
$("div a[href^='http']").each(function() {
$(this).attr("alt",altText);
var oldClassAttributeValue = $(this).attr("class");
if(!oldClassAttributeValue) {
$(this).attr("class",newClassAttributeValue);
}
});您可以对其进行修改以添加文本。类也可以使用css函数进行修改。
https://stackoverflow.com/questions/290368
复制相似问题