JQuery多次点击事件?

时间:2013-10-15 02:54:43

标签: jquery

我的页面中有两个div。

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

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

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

但是如何实现两个div与上面类似的语句点击要监视的事件,以及如何区分div,这是click事件?

6 个答案:

答案 0 :(得分: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
})

答案 1 :(得分:2)

只需在回调函数中使用$(this)即可知道事件触发的'哪个'元素。

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

答案 2 :(得分: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

答案 3 :(得分: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

答案 4 :(得分: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
});

答案 5 :(得分:-2)

可能是这样的:

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

在定义元素之前,不能使用该元素。