how to bind 2 events with JQuery's .on method

可紊 提交于 2021-01-29 07:44:39

问题


I have this code which is working great on already created divs

$('.MyDivs').click(function(){
      $('#OtherDiv').css('display','block');
}).mouseleave(function(){
      $('#OtherDiv').css({ display: 'none' });
});

but does not work on dynamically created new Divs. I know there is a .on method of Jquery for dynamically created divs but do not know how to bind 2 events with it. I tried something like this

$(document).on('click', '.MyDivs', function()
{
     $('#OtherDiv').css('display','block');
}).mouseleave(function(){
     $('#OtherDiv').css({ display: 'none' });
});

I also tried this

$(document).on('click', '.MyDivs', function()
{
     $('#OtherDiv').css('display','block');
});
$(document).on('mouseleave', '.MyDivs', function()
{
     $('#OtherDiv').css({ display: 'none' });
});

but does not work. How can I bind click and mouseleave methods with .on?

My Problem

I just want to show Otherdiv on click of any div which has .MyDivs class and hide Otherdiv when mouse leaves currently .MyDivs div


回答1:


you can try this. This should work.

$(document).on({
    mouseenter: function() {
        // Handle mouseenter...
    },
    mouseleave: function() {
        // Handle mouseleave...
    },
    click: function() {
        // Handle click...
    }
}, ".MyDivs");



回答2:


You need to use on for each chain. This should work:

$(document).on('click', '.MyDivs', function() {
    $('#OtherDiv').css('display','block');
}).on('mouseleave', '.MyDivs', function() {
    $('#OtherDiv').css('display','none'});
});

Or you can bind both events and look for the event.type, then toggle the div depending on the result:

$(document).on('click mouseleave', '.MyDivs', function(e) {
    $('#OtherDiv').toggle( e.type == 'click' );
});


来源:https://stackoverflow.com/questions/21579250/how-to-bind-2-events-with-jquerys-on-method

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