打印本页〗〖打印选项
XHTML 中 a 标签 target 属性失效的解决方法
  在HTML 4.01/XHTML 1.0/XHTML 1.1严格DOCTYPE(XHTML 1.0 Strict)下,<a>标签的target属性失效,即target="_blank"等控制将失效,无法通过W3C的校验,只有采用过渡型的DOCTYPE(XHTML1-transitional.dtd)。

  为了严格地通过W3C的校验,我们只有想办法避免使用target属性。我看到有人在网上提出在<head>元素中加入:<base target="_blank" />。<base>是一个链接基准标记,用以改变页面中所有链接标记的参数默认值。表面上这样可以避免问题,但是我们从官方资料上可以看到,base标签的target属性已经被去掉了,并且base被强制要求加入href属性http://liorean.web-graphics.com/xhtml/comparison.loose-strict.html。因此,此法肯定不行。

  我在网上搜集了两种方法,都是用JS解决的。从理论上讲,这些应该是最好的方法了。

1.使用CSS+JS,比较规范,但是如果浏览器屏蔽弹出窗口,就不好使了
<script>
function test1()
{
window.open(this.href,"","");
return false
}
function test2()
{
window.open(this.href,"51windows","top=10,height=10,width=240,height=180");
return false
}
</script>

<style>
.newwin1 {haiwa:expression(this.onclick=test1)}
.newwin2 {haiwa:expression(this.onclick=test2)}
</style>

<a href="about:blank" class=newwin1>新窗口</a><br />
<a href="about:blank" class=newwin2>新窗口</a><br />

2.单纯使用JS,在需要的<a>标签中加入rel=external。当然,你也可以把external换成别的,前提是你要看懂下面的程序,并加以修改。
function outlinks() {
   if (!document.getElementsByTagName) return;
   var anchors = document.getElementsByTagName("a");
   for (var i=0; i<anchors.length; i++) {
     var anchor = anchors[i];
     if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "external")
     anchor.target = "_blank";
   }
}

     虽然问题可以解决,但仍然是不舒服的,因为在HTML时代很简单的一件事情,现在变得如此麻烦。我总觉得XHTML这个标准在这里是不是有点不合理,或许真的有他的道理,希望能见到更好的官方或者民间的解决方法。



文章作者:未知