简体   繁体   English

jQuery单击可见元素处理程序之一

[英]Jquery click on one of visible elements handler

When my modal window is visible, when i click on #screen or on #loading_modal i need to hide this div's, but how can i do that, and how to write it correctly, now my code is not working, but also i have same for two objects (#screen, #loading_modal).... I'm new in js, how to refactor this code, and make it working properly... ? 当我的模态窗口可见时,当我单击#screen或#loading_modal时,我需要隐藏该div,但是我该怎么做以及如何正确编写它,现在我的代码不起作用,但是我也有对于两个对象(#screen,#loading_modal)。...我是js的新手,如何重构此代码,并使其正常工作...?

  if ($('#screen').is(':visible')) {
    $("#screen").click(function() {    
      $('#screen').hide();
      $('#loading_modal').hide();  
    });
     $("#loading_modal").click(function() {    
      $('#screen').hide();
      $('#loading_modal').hide();  
    });
  } 

If I have understood you correctly I think you need to put the check for visibility inside the click handlers like so: 如果我对您的理解正确,我认为您需要将可见性检查放在如下所示的点击处理程序中:

$("#screen").click(function() {    
    if ($('#screen').is(':visible')) {
        $('#screen').hide();
        $('#loading_modal').hide();  
    }
});
$("#loading_modal").click(function() {    
    if ($('#screen').is(':visible')) {
        $('#screen').hide();
        $('#loading_modal').hide();  
    }
});

No need for the if statement here, you can simply use: 这里不需要if语句,您可以简单地使用:

$('element:visible').click(function() { ... })

So: 所以:

$("#screen:visible").click(function() {    
    $(this).hide();
    $('#loading_modal').hide();  
});
 $("#loading_modal:visible").click(function() {    
    $('#screen').hide();
    $(this).hide();  
});

If the functions are going to perform identical tasks, you can simply use: 如果这些功能将执行相同的任务,则可以简单地使用:

$("#screen:visible, #loading_modal:visible").click(function() {    
    $('#screen').hide();
    $('#loading_modal').hide();  
});

you are doing wrong. 你做错了。 you can check the Condition in click event. 您可以检查点击事件中的条件。 once the click event fired. 点击事件触发后。 put if conditon in side the click event handler if conditon在侧点击事件处理

$("#screen").click(function() {    
    if ($('#screen').is(':visible')) {
        $('#screen').hide();
        $('#loading_modal').hide();  
    }
});
$("#loading_modal").click(function() {    
    if ($('#screen').is(':visible')) {
        $('#screen').hide();
        $('#loading_modal').hide();  
    }
});

You can just refactor your code to look like this 您可以将代码重构为如下所示

$("#screen,#loading_modal").click(function() { 
      $('#screen,#loading_modal').hide();       
});

There's no need to check if it's visible 无需检查是否可见

If it's dynamically created, you will need to delegate or bind after creation of the elements 如果是动态创建的,则在创建元素后需要委托或绑定

$('body').on('click',"#screen,#loading_modal",function() { 
      $('#screen,#loading_modal').hide();       
});

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

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