onclick() not working in safari

回眸只為那壹抹淺笑 提交于 2019-12-11 03:24:11

问题


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.

<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]

 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);
 }

回答1:


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

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




回答2:


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?



来源:https://stackoverflow.com/questions/6682302/onclick-not-working-in-safari

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!