Manually trigger mouseover event without allowing the event to propagate

∥☆過路亽.° 提交于 2019-12-10 19:49:07

问题


How can I trigger mouseover event using jQuery just for a specific element, without allowing the event to propagate to the parent controls.

I know how to trigger the event: $('selector').trigger('mouseover');

For example I have an image inside tr. I have hover event handlers for both of them. I want to manually trigger hover-in event just for the image.

Does anyone have an idea?


回答1:


I found the answer looking in the examples here. Here is the code solving my problem:

var event = jQuery.Event('<event_name>');
event.stopPropagation();
$('<selector>').trigger(event);



回答2:


You can attach the mouseover as a normal event listener and then do something like this.

$("selector").on('mouseover', function(event){
  event.stopPropagation();
  // do something
}); 

This will stop the event bubbling up to the container elements. You can then call your trigger as you normally would

$('selector').trigger('mouseover');



回答3:


Use mouseenter or event.stopPropagation() like

$("img").on('mouseover', function(e){
    e.stopPropagation();
    // do something
});

or

$("img").on('mouseenter', function(e){
    // do something
});

Read mouseenter() and mouseover()



来源:https://stackoverflow.com/questions/18334308/manually-trigger-mouseover-event-without-allowing-the-event-to-propagate

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!