Eventlistener并不总是调用jquery ui图标

时间:2018-05-23 15:05:59

标签: jquery jquery-ui

作为UI字体我加载

<head>
    <meta charset="utf-8" />
    <script src="/javascripts/jquery-ui-1.12.1.custom/external/jquery/jquery.js"></script>
    <script src="/javascripts/jquery-ui-1.12.1.custom/jquery-ui.js"></script>
    <link href="/javascripts/jquery-ui-iconfont-master/jquery-ui.icon-font.css" rel="stylesheet" type="text/css" />
</head>

在用于播放器的页面中

<div id="iconStop" class="ui-icon ui-icon-stop">icon</div>
<div id="iconRecord" class="ui-icon ui-icon-radio-on">icon</div>
<div id="iconPause" class="ui-icon ui-icon-pause">icon</div>

比那个

function sendCommand(name){
      sendJson('mode:'+name);
 }
 window.onload = function () {
       document.getElementById("iconStop").addEventListener("click",function(){ sendCommand('stop'); } );
       document.getElementById("iconRecord").addEventListener("click",function(){ sendCommand('record'); } );
       document.getElementById("iconPause").addEventListener("click",function(){ sendCommand('pause'); } );
   }
奇怪的是,点击有时只能起作用。 sendCommand('any')的手动调用始终有效! 知道为什么那不总是有效吗?

2 个答案:

答案 0 :(得分:1)

加载jquery并使用纯javascript处理事件可能有些棘手。在你的情况下,我推荐这样的东西:

function sendCommand(name){
    sendJson('mode:'+name);
}
$(document).ready(function(){

    $('#iconStop').on('click', function() { sendCommand('stop'); } );
    OR
    $('#iconStop').click(function() { sendCommand('stop'); } );
})

这里的主要区别是,还有页面就绪和jquery。我的代码使用jquery监听器,所以不应该有听众互相碰撞的情况。

答案 1 :(得分:0)

实际上通过将事件更改为mousedown(例如

),修复很简单
window.onload = function () {
    document.getElementById("iconStop").addEventListener("mousedown",function(){ sendCommand('stop'); } );
    document.getElementById("iconRecord").addEventListener("mousedown",function(){ sendCommand('record'); } );
    document.getElementById("iconPause").addEventListener("mousedown",function(){ sendCommand('pause'); } );
}

至少对于firefox和chrome来说效果要好得多