2011-02-25 48 views
0
<input id="button" type="button" onclick="javascript:alert('hello')"> 
<a href='http://google.com' onclick="javascript:alert('hello')">Google</a> 

想要触发点击事件。 在地址栏中的URLJavascript单击事件不是触发标记

javascript:document.getElementById("button").click(); //working find 
javascript:document.getElementsByTagName("a")[0].click(); //not working, Why 

这基本上是自动点击按钮,接受/拒绝了Facebook的所有请求。

回答

2

JavaScript不支持单击锚点(<a>标记)。但是,有一种解决方法:使用一些自定义JavaScript代码,您可以模拟锚点上的点击。

这是我创建的短片段。它模拟你期望的动作,甚至是你使用目标属性。我建立了一个检查,看看这个方法是否真的在一个锚点上运行,所以你甚至可以在你的按钮上使用这个方法,并期望正常的行为。你只需要将它添加到你的页面的某个地方。我测试了它在Safari 5

Element.prototype.anchorClick = function() { 
    if (this.click) return this.click(); 
    if (this.onclick) { var result = this.onclick(); if (!result) return result; } 

    switch (this.target) { 
     case '_blank': window.open(this.href); break; 
     case '_parent': parent.location = this.href; break; 
     case '_top': top.location = this.href; break; 
     case '_self': case '': window.location = this.href; break; 
     default: if (parent[this.target]) parent[this.target].location = this.href; else window.open(this.href); break; 
    } 

    return true; 
} 

您使用的片段是这样的:

javascript:document.getElementById('anchor').anchorClick(); 
javascript:document.getElementsByTagName('a')[0].anchorClick(); 

这里完整版本的一些意见里面:

Element.prototype.anchorClick = function() { 
    // If there's a click method, the element isn't an anchor 
    if (this.click) { 
     // Just run the click method instead 
     return this.click(); 
    } 

    // Is there an onclick method? 
    if (this.onclick) { 
     // Run the method and get the result 
     var result = this.onclick(); 

     // Isn't the result true? 
     if (!result) { 
      // Cancel the operation and return the result 
      return result; 
     } 
    } 

    // Check the target property 
    switch (this.target) { 
     // _blank means a new window 
     case '_blank': 
      // Open the window 
      window.open(this.href); 
      break; 

     // _parent means the parent frame 
     case '_parent': 
      parent.location = this.href; 
      break; 

     // _top means the top frame 
     case '_top': 
      top.location = this.href; 
      break; 

     // _self means the current frame 
     // When there's no value for the target property, this is the expected result 
     case '_self': 
     case '': 
      window.location = this.href; 
      break; 

     // The last option is a user specified frame 
     default: 
      // Does the frame actually exist? 
      if (parent[this.target]) { 
       // Yep, and we'll open the page in that frame 
       parent[this.target].location = this.href; 
      } else { 
       // Nope, the frame doesn't exist 
       // The expected behaviour (in Safari) is opening a new window 
       window.open(this.href); 
      } 

      break; 
    } 

    return true; 
} 
0

onclick在Chrome工作对我来说和Firefox3.6:

javascript:document.getElementsByTagName("a")[0].onclick();