简体   繁体   English

将JQuery点击事件直接指向两个相同元素?

[英]Direct JQuery click events to two of same element?

I have a webpage which loads a slider/drawer. 我有一个加载滑块/抽屉的网页。 Inside the webpage, I load an html div for the contents of the drawer for when the window is expanded, and another duplicate of it for when the window is collapsed in a small window like on a phone. 在网页内部,我为加载窗口时抽屉的内容加载了一个html div,并为当窗口在电话中的小窗口中折叠时加载了另一个html div。

On the page is have a function like 在页面上有一个类似的功能

$('#button').click(function(){
  //do something
});

The large button of 的大按钮

<div id="button">
 //button here
</div>

loads before the small version. 在小版本之前加载。 So clicking the large one works and the .click event is triggered, but for the small one it isn't. 因此,单击较大的控件将起作用,并且会触发.click事件,但对于较小的控件则不会。

How can I get my .click function to observe the click event on the small drawer when it's clicked? 如何获得我的.click函数以观察小抽屉被单击时的单击事件?

If I understand the situation correctly, you are in need of a single function which handles click events from multiple elements. 如果我正确了解情况,则需要一个功能来处理来自多个元素的点击事件。

I would not use IDs for the elements, but instead use a class to decorate the ones that need the functionality. 我不会为元素使用ID,而是使用类来装饰需要功能的元素。 Then using 'this', I can further modify the item that was clicked... 然后使用“ this”,我可以进一步修改单击的项目...

$('.myClickable').click(function(){
  $(this).someFunc();
});

Use same class, different ids: 使用相同的类,使用不同的ID:

$('.button').click(function(){
var foo=$(this).attr('id');
alert(foo);
});

html: HTML:

<div class="button" id="bar">
</div>

<div class="button" id="moo">
</div>

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

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