简体   繁体   English

jQuery组合的单击和悬停功能仅适用于单击,不适用于悬停

[英]jquery combined click and hover function only works for click, not working for hover

My question is fairly simple but confusing. 我的问题很简单,但令人困惑。 I have combined "click" and "hover" by using .on(), but the function is only firing when click, not hover. 我已经通过使用.on()组合了“ click”和“ hover”,但是该函数仅在单击时触发,而不是悬停。

JS: JS:

    var hoverElem = null;
    $("table tbody tr td").on('click hover', function(e){
        alert("TDDDDD!!!!");

    });

The html part is a simple html table. html部分是一个简单的html表。

Does anyone know why? 有人知道为什么吗?

Just wondering how click and hover working together, because when you mouseover itself event is fired. 只是想知道单击和悬停如何一起工作,因为当您将鼠标悬停在其自身上时,会触发事件。

this is the example using fiddle 这是使用小提琴的例子

var hoverElem = null;
$("div").on('click mouseover', function(e){
    alert("TDDDDD!!!!");

});

I think you have to use 'mouseover' rather than 'hover', which isn't listed in the events: http://api.jquery.com/Types/#Event . 我认为您必须使用'mouseover'而不是'hover',该事件未列出: http : //api.jquery.com/Types/#Event There is a separate hover function, though: http://api.jquery.com/hover/ . 不过,还有一个单独的悬停功能: http : //api.jquery.com/hover/

I don't know WHY it doesn't work when you put the hover in jQuery on, but if you use jQuery hover instead, it works. 我不知道为什么当您将鼠标悬停在jQuery上时它不起作用,但是如果使用jQuery悬停,它将起作用。 Click the button below to run the code. 单击下面的按钮以运行代码。

 $(function() { function my_function(e) { alert("TDDDDD!!!!"); }; $("table tbody tr td").on('click', function(e) { my_function(e); }) .hover(function(e) { my_function(e); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr> <td>test</td> </tr> </table> 

There's just slightly different syntax for multiple events in the same on() . 同一on()多个事件的语法略有不同。

$( "table tbody tr td" ).on({
  click: function() {
    alert("TDDDD!!");
  }, 
  hover: function() {
    alert("TDDDD!!");
  }
});

This has repeated code, so just create a function: 这有重复的代码,因此只需创建一个函数:

alertFunc = function() {
  alert("TDDDD!!!");
};
$( "table tbody tr td" ).on({
  click: alertFunc, 
  mouseover: alertFunc
});

See the example for handling multiple events at: http://api.jquery.com/on/ (Look for: "Example: Attach multiple event handlers simultaneously using a plain object.") 请参见以下示例,以处理多个事件: http : //api.jquery.com/on/ (查找:“示例:使用一个普通对象同时附加多个事件处理程序。”)

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

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