JQuery多次点击事件?

7
在我的页面中有两个div。
<div id="test-1000"></div>
<div id="test-1111"></div>

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

考虑到上述单击事件的来源,jQuery是:

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

但是如何实现两个具有类似于上述语句的div,以便对它们进行监视点击事件,并且如何区分哪个div是点击事件?


传递到点击事件中的事件将保存对实际被单击的元素的引用,因此您可以通过该方法轻松地识别它...通常 [ .click(function(evt){evt.target}) ] - ermagana
6个回答

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') );
});

0

我更喜欢使用数据属性和类的方法

HTML代码

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

js

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

示例 演示


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
});

-2

也许类似这样:

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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接