简体   繁体   English

如何以编程方式在javascript中触发dbclick事件?

[英]How to programmatically fire ondblclick event in javascript?

I am trying the following simple code (in html, using js on IE8): 我正在尝试以下简单的代码(在html中,在IE8上使用js):

<input type="image" src="pic.jpg" id="aa" ondblclick="alert('aa');"/>
<script>
document.getElementById('aa').dblclick(); 
</script>

and I get an error that: object doesn't support this property or method (regarding the script part). 我得到一个错误:对象不支持此属性或方法(关于脚本部分)。 And I don't get the alert. 我没有得到警报。

Whereas when I dblclick on the image, I get the alert message. 然后当我点击图像时,我收到警报消息。 So I wish to know how to programmatically fire the dblclick event (without actually double clicking the image). 所以我想知道如何以编程方式触发dblclick事件(实际上没有双击图像)。

The same works just fine with onclick (instead of on dblclick). 使用onclick(而不是dblclick)也可以正常工作。 I also tried it on button, input text. 我也尝试了按钮,输入文字。 Same error . 同样的错误。

The property name is ondblclick but you're attempting to call dblclick . 属性名称是ondblclick但您尝试调用dblclick You need to call ondblclick . 你需要调用ondblclick

<script>
  document.getElementById('aa').ondblclick(); 
</script>

Fiddle: http://jsfiddle.net/frwpY/ 小提琴: http//jsfiddle.net/frwpY/

try this: 尝试这个:

<input type="image" src="pic.jpg" id="aa" ondblclick="alert('aa');"/>
<script>
document.getElementById('aa').ondblclick(); 
</script>

http://jsfiddle.net/dnUZY/1/ http://jsfiddle.net/dnUZY/1/

Check out MDNs article about element.dispatchEvent 查看有关element.dispatchEvent MDN文章

Sample code from MDN: 来自MDN的示例代码:

function simulateClick() {
  var evt = document.createEvent("MouseEvents");
  evt.initMouseEvent("click", true, true, window,
    0, 0, 0, 0, 0, false, false, false, false, 0, null);
  var cb = document.getElementById("checkbox"); 
  var canceled = !cb.dispatchEvent(evt);
  if(canceled) {
    // A handler called preventDefault
    alert("canceled");
  } else {
    // None of the handlers called preventDefault
    alert("not canceled");
  }
}

This way you can also track the event through the DOM bubble and make sure it wasn't canceled. 这样,您还可以通过DOM气泡跟踪事件,并确保它未被取消。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM