【问题标题】:Understanding HTML anchor tag了解 HTML 锚标记
【发布时间】:2010-10-09 17:50:27
【问题描述】:

让我们从下面的例子开始:

在同一目录下创建三个页面: 测试.html index.html

你的 test.html:

<html>
 <head>
  <script>
   function test()
   {
    alert('Going to google.com?');
    window.location="http://google.com";
   }
  </script>
 </head>
 <body>
  <a href='' onclick="test();">google.com</a><br/>
  <input type="button" value="google" onclick="test();" />
  <a href='' onmouseover="test();">google.com</a><br/> 
 </body>
</html>

现在在 IE 以及 firefox 或 crome 上检查 test.html 页面。

你会注意到以下几点:

  1. 按钮完美运行。
  2. 第一个超链接在 IE 和其他浏览器中的工作方式不同。在 IE 中,它让我们回到 index.html 页面,而在 Firefox 中,它停留在同一页面上。
  3. 对于第一个超链接,window.location 失败。
  4. 您不能点击第二个超链接,因为鼠标悬停事件将首先触发,而且效果很好!

为什么?

我的主要兴趣在于第三点,因为它甚至给了我们警报,window.location 失败了。

【问题讨论】:

    标签: javascript html internet-explorer firefox anchor


    【解决方案1】:

    JavaScript 事件触发,window.location 被设置,然后链接的默认操作触发并且浏览器转到 '',它 (IIRC) 解析为当前 URI。

    这与单击一个链接然后快速单击另一个链接所获得的效果相同。浏览器在收到跳转到第二个的指令之前来不及跳转到第一个,就跳转到了第二个。如果您延迟函数的返回(通过将警报放在第二个),它会为第一个 URL 的请求提供足够的时间来访问该 URL 而不是第二个。

    您需要取消默认操作,当您使用内部事件属性时(不推荐,unobtrusive JavaScript 是前进的方向),通过返回 false 来完成。

    onclick="test(); return false;"
    

    【讨论】:

      【解决方案2】:

      试试这个:

      <html>
       <head>
        <script>
         function test()
         {
          alert('Going to google.com?');
          window.location="http://google.com";
          return false;
         }
        </script>
       </head>
       <body>
        <a href='' onclick="Javascript:return test();">google.com</a><br/>
        <input type="button" value="google" onclick="Javascript:return test();" />
        <a href='' onmouseover="Javascript:return test();">google.com</a><br/> 
       </body>
      </html>
      

      【讨论】:

      • 如果我把alert()放在window.location之后,那么alert()会首先被调用,然后它会将我们重定向到我们的位置,为什么?
      • 其实我在 js 方面没有经验告诉你为什么在重定向之前会出现警报。对我来说,重定向似乎是在 window 对象的 location 属性更改时触发的,并且该事件被放在堆栈上并在您的 test() 方法中正在处理的 click 事件之后进行处理
      猜你喜欢
      • 2016-01-30
      • 2010-09-06
      • 1970-01-01
      • 2013-09-07
      • 1970-01-01
      • 2022-08-12
      • 2019-03-27
      • 2022-12-12
      • 1970-01-01
      相关资源
      最近更新 更多