onclick()不适用于Safari浏览器 [英] onclick() not working in safari

查看:704
本文介绍了onclick()不适用于Safari浏览器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码在IE7上正常工作,但在Safari(5.0.5)中无法正常工作。如果可能的话,我想避免使用jQuery。目标是在iPad上使用此功能,但现在正在使用桌面Safari进行测试。请让我知道,如果你有任何想法让它在IE和Safari浏览器上都能正常工作。


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>

更新:辩论是否使用onmouseup或类似下面的内容[ Thanks Andres < /强> !!我不能添加评论]

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


推荐答案

你有的是,你不能在< img> 上调用 click()。这并不意味着 onclick 处理程序不起作用。如果你拿着鼠标点击图片,处理程序仍然会触发。

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.

这篇关于onclick()不适用于Safari浏览器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆