2013-10-15 169 views
7

我的页面有两个div。JQuery多重点击事件?

<div id="test-1000"></div> 
<div id="test-1111"></div> 

鉴于上述单一的点击事件源jQuery是:

$('#test-1000').click(function(){}); 

但如何实现两个DIV有类似被监控上述声明的点击事件,以及如何区分div,这是点击事件?

+0

传递到click事件将举行被点击的实际元素的引用的情况下,让您轻松通过该方法识别它...通常[.click(function(evt){evt.target})] – ermagana

回答

10

我将使用一个通用类属性组中的所有目标元素

<div class="test" id="test-1000" data-id="1000"></div> 
<div class="test" id="test-1111" data-id="1111"></div> 

然后

$('.test').click(function(){ 
    //here this.id will give the clicked div id and this will refer the clicked dom element 
    //$(this).data('id') will give 1000/1111 
}) 
2

只需使用$(this)在回调函数知道“这”元素的情况下开火。

$('.test').click(function() { 
    alert($(this).attr('id')); 
}); 
-2

也许是这样的:

document.getElementById("test-1000").onclick = function(){}); 

不能被定义之前使用的元素。

0

我宁愿去与数据属性和类方法

HTML代码

<div class="test" data="0000">1</div> 
<div class="test" data="1111">2</div> 

JS

$('.test').click(function(){ 
    alert($(this).attr("data")); 
}); 

样品demo

0

或者,如果你不想或者不能修改你的html,你可以使用jquery "starts-with" selector

<div id="test-1000"></div> 
<div id="test-1111"></div> 

$("[id^='test']").on('click', function(){ 
    console.log(this.id); 
}); 

JsFiddle

0

HTML

<div class="test" id="test-1000" data-id="1000"></div> 
    <div class="test" id="test-1111" data-id="1111"></div> 

的js

$('.test').click(function(){ 
    //here this.id will give the clicked div id and this will refer the clicked dom element 
    //$(this).data('id') will give 1000/1111 
});