javascript onclick() 在 safari 中不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6682302/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 21:30:14  来源:igfitidea点击:

onclick() not working in safari

javascripthtmlsafarionclick

提问by user127091

The below code works fine on IE7 but not in Safari(5.0.5). If possible, I want to avoid using jQuery. The goal is for this functionality to work on iPad but right now testing with desktop safari. Please let me know if you have any ideas on getting it to work both on IE and Safari.

下面的代码在 IE7 上运行良好,但在 Safari(5.0.5) 中不起作用。如果可能,我想避免使用 jQuery。目标是让此功能在 iPad 上运行,但目前正在使用桌面 safari 进行测试。如果您有任何关于让它在 IE 和 Safari 上工作的想法,请告诉我。

<div id="test" ></div>
<script>
  function attachCallback(node) {
    node.onclick = function() {   
      alert("coming here");
    } ;
  }  
  var retrybutton = document.createElement("img");
  retrybutton.src = "test.png";
  retrybutton.alt = "retry";

  retrybutton.setAttribute("id","retrybutton");
  attachCallback( retrybutton ) ;

  var a = document.getElementById("test");
  a.appendChild(retrybutton);
  // testing without using retrybutton
  var test = document.getElementById("retrybutton");
  test.click();
</script>
</body></html>

Update: Debating whether to go with "onmouseup" or something like below [Thanks Andres!! I'm not able to add comments]

更新:辩论是否使用“onmouseup”或类似下面的内容[谢谢安德烈斯!!我无法添加评论]

 if (Prototype.Browser.IE) {
   document.getElementById("retrybutton").click(); 
 } else { // from question link in comment
   var event = document.createEvent("HTMLEvents");
   event.initEvent("click", true, true);
   document.getElementById('retrybutton').dispatchEvent(event);
 }

回答by gilly3

In Safari, the click()method (which simulates a mouse click) cannot be applied to an <img>. But, it can be applied to an <input type="image">. Are you able to use that?

在 Safari 中,该click()方法(模拟鼠标单击)不能应用于<img>. 但是,它可以应用于<input type="image">. 你能用那个吗?

回答by Abhay Buch

As gilly3 noted, the issue you're having is that you cannot call click()on an <img>. This does not mean that the onclickhandler does not work. If you take your mouse and click on the image, the handler will still fire.

作为gilly3注意到,您遇到的问题是,你不能调用click()<img>。这并不意味着onclick处理程序不起作用。如果您用鼠标单击图像,处理程序仍将触发。

Now, if you want to simulate the click, this answerwill give you everything you need to do that.

现在,如果您想模拟点击,此答案将为您提供执行此操作所需的一切。