下一步,我们通过getElementsByTagName方法取得文档里所有的<a>标签: var anchors = document.getElementsByTagName("a");
anchors被赋值为包含各个<a>标签的数组,现在我们必须遍历各个<a>标签并且修改它: for (var i=0; i < anchors.length; i ) { var anchor = anchors; 找到要实现新开窗口的<a>标签 if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "external")
function externalLinks() { if (!document.getElementsByTagName) return; var anchors = document.getElementsByTagName("a"); for (var i=0; i<anchors.length; i ) { var anchor = anchors; if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "external") anchor.target = "_blank"; } } window.onload = externalLinks;