简体   繁体   English

如何在单击函数中绑定jquery中的2个元素

[英]how to bind 2 elements in jquery on click function

For closing a modal with the class submitmodal i use this code and it works fine. 要使用类submitmodal关闭模态,我使用此代码,它工作正常。

$('.submitmodal').click(function() {          
      window.location.hash='close';
});

For click on the body somewhere i use this: 点击身体的某个地方我用它:

$('body').click(function() {          
      window.location.hash='close';
    });

How can i merge them together? 我如何将它们合并在一起?

I tried this but it does not work 我试过这个,但它不起作用

$('.submitmodal', 'body').click(function() {          
      window.location.hash='close';
    });

Try 尝试

(".submitmodal, body").click(function() {          
      window.location.hash="close";
});

The selectors have to be in the same string, seperated by a comma. 选择器必须在同一个字符串中,用逗号分隔。

Try this : 尝试这个 :

    $(document).on("click",'body',function(){
       window.location.hash='close';
    })

This should do it 这应该做到这一点

$('.submitmodal, body').click(function() {          
    window.location.hash = 'close';
});

You can use Multiple selector using first selector, second selector 您可以使用first selector, second selector使用多选择first selector, second selector

$('body,.submitmodal').click(function() {          
          window.location.hash='close';
        });

You can specify any number of selectors to combine into a single result. 您可以指定任意数量的选择器组合成单个结果。 This multiple expression combinator is an efficient way to select disparate elements. 这种多表达式组合子是选择不同元素的有效方法。 The order of the DOM elements in the returned jQuery object may not be identical, as they will be in document order. 返回的jQuery对象中DOM元素的顺序可能不相同,因为它们将按文档顺序排列。

$("body, .submitmodal").click(function() {          
      window.location.hash="close";
});

For More help see this : multiple-selector I hope it helps you :), Thanks. 更多帮助看到这个: 多选择器我希望它可以帮助你:),谢谢。

This should solve your issue: 这应该可以解决您的问题:

$('.submitmodal, body').click(function() {          
      window.location.hash='close';
});

But the problem I see is that when you click anywhere over the body you are closing your modal and that includes when you click over the element that opens itself. 但我看到的问题是,当你点击身体的任何地方时,你正在关闭模态,包括当你点击打开自身的元素时。 So I would suggest you to write something like that: 所以我建议你写一下这样的东西:

$('body, .submitmodal').click(function(e) {  
      if (e.target !== this) return;  //prevents body's child elements from being affected
      window.location.hash='close';
});

I've done some tests and apparently 'this' references to the first selector (body) which is fine for this situation. 我做了一些测试,显然'this'引用了第一个选择器(主体),这对于这种情况很好。

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

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