JQuery one click event for multiple element events
My question is related to this one: jQuery same click event for multiple elements
However, when I do:
$('.class1, .class2').click(function() {
some_function();
});
I always use the same function with the same object. What if I wanted to consolidate the following two statements for instance:
$(".class1").click(function () {
$(".classer1").slideToggle("slow");
});
$(".class2").click(function () {
$(".classer2").slideToggle("slow");
});
They reference a different object for each - can I even consolidate this?
Thanks, Oliver
You could do this:
$(".class1, .class2").click(function () {
$(".classer"+$(this).attr('class').substr(-1)).slideToggle("slow");
});
as long as the elements you're clicking on only have one class. This pulls the integer off the element being clicked on and appends it to .classer
. So clicking on .class2
would trigger the toggle on .classer2
.
You might want to take a look at add(). Use it to add selectors to the selection stack. Use it like this:
$('.class1').add('.class2').click(function (e) {
// Do whatever you want
})
I think the best way to do this is to add a data attribute to the reference number you are using for each of the classes so if you have something like
<div class="class1" data-ref-id="1"></div>
and
<div class="class2" data-ref-id="2"></div>
You could find your referenced toggle class like so:
$('.class1, .class2').click(function (e) {
$('.' + NAME_OF_REFERENCED_TOGGLE_CLASS + this.data.refId).slideToggle('slow');
})
链接地址: http://www.djcxy.com/p/83450.html
上一篇: 将两个元素传递给Jquery的一个函数
下一篇: JQuery单击事件多个元素事件