2011-02-25 66 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();