简体   繁体   English

无法触发jQuery中的事件

[英]Unable to trigger events in jQuery

I want to trigger a context menu event in jQuery on a audio element. 我想在音频元素上的jQuery中触发上下文菜单事件。 Here is the code: 这是代码:

$("audio").contextmenu();

However, this does not show a context menu for the element. 但是,这不会显示该元素的上下文菜单。 I thought maybe there is need for some user interaction so I wrapped it in a moueenter event. 我认为可能需要一些用户交互,因此我将其包装在一个moueenter事件中。

$("audio").on("mouseenter", function(e) {
   $(this).contextmenu();
}

However, the context menu still does not appear. 但是,上下文菜单仍然不会出现。 Finally, I decided to do the right click on the audio element manually and trigger a key press event but it also did not seem to do anything. 最后,我决定手动在音频元素上单击鼠标右键并触发按键事件,但它似乎也无能为力。

$("audio").on("contextmenu", function(e) {
  var code = 86;
  $(this).trigger(
    jQuery.Event( 'keydown', { keyCode: code, which: code } )
  );
});

This code snippet was supposed to trigger a jQuery keypress event with "v" pressed. 该代码段应该在按下“ v”时触发jQuery按键事件。

When we right click on an audio element and press "v", it shows a save audio as dialog. 当我们右键单击音频元素并按“ v”时,它将显示一个“将音频另存为”对话框。 I wanted to write the code to trigger the context menu and keypress programatically but none of them seem to have any effect. 我想编写代码以触发上下文菜单并以编程方式按键,但是它们似乎都没有作用。 Why is that? 这是为什么?

You can trigger the right click menu on your audio element but only if you right click on it. 您可以触发音频元素上的右键菜单,但前提是您右键单击它。 Be sure to add the 'controls' attribute to your audio element so that there would be something to click on. 确保将“ controls”属性添加到您的音频元素,以便单击某些内容。 Try it on the code below. 在下面的代码上尝试一下。

 $("audio").on("contextmenu", function(e) { alert("Hello Context Menu!"); }); $("button").on("click", function(){ $("audio").contextmenu(); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <audio id="t-rex-roar" controls src="https://soundbible.com/mp3/Tyrannosaurus%20Rex%20Roar-SoundBible.com-807702404.mp3"> </audio> <button>Call Context Menu Event for Audio Element, Event only</button> 

However , you can't add a button click event that displays the context menu for another element; 但是 ,您不能添加显示另一个元素的上下文菜单的按钮单击事件。 Programmatically Calling Browser Right-Click Menu Options? 以编程方式调用浏览器的右键单击菜单选项?

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

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