当页面上有多个具有相同选择器的按钮时,请检查单击了哪个exatly按钮

Check what exatly button clicked, when multiple buttons with the same selector on page

本文关键字:按钮 检查 单击 exatly 选择器      更新时间:2023-09-26

我有两个具有相同选择器类的按钮。当我这样做时:

$('.my_button').click(function() {
    console.log(1);
});

,然后单击它记录1的按钮两次,就像我单击了两个按钮而不是单个按钮一样。所以我的问题是:JS中存在某种方法,可以只获取我单击的按钮,而不分配像id这样的唯一选择器。我是JS的新手,有人能解释一下吗?我在这里找到了相关的问题。谢谢

编辑:

我做的纽扣有点不同。是的,它只返回一个按钮,但为什么点击触发器能工作两次。控制台日志记录两次。

每个事件侦听器都接收事件,该事件携带事件目标。试试下面的例子。

$('.my_button').click(function(e) {
    console.log(e);
    console.log(e.currentTarget);
    console.log($(e.currentTarget));
});

在函数代码中使用this

$('.my_button').on('click',function() {
    var tempContainer=$(this).parent();
    alert($(tempContainer).html());   // you ll see that you are showing the code where exists your clicked button
});

为按钮分配不同的id

$(".my_button").on("click",function(){
  console.log($(this).attr("id"))
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" class="my_button" id="test" value="Test"/>
<input type="button" class="my_button" id="test2" value="Test-2"/>

试试这个:

<button class="my_button">Content1</button>
<button class="my_button">Content2</button>
<script>
$( ".my_button" ).click(function( event ) {
console.log(1);
});
</script>

https://jsfiddle.net/nt9ryeyr/5/

试试这个:-

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $(".p").click(function(e){
        alert($(e.currentTarget).attr("value"));//button text on which you clicked
    });
});
</script>
</head>
<body>
<input type='button' class="p" value='test'/>
</body>
</html>

如果你的html像这个

<button class="my_button">Test</button>
<button class="my_button">Test1</button>

然后使用这个脚本

$('.my_button').click(function() {
if(this.innerHTML ==="Test")
    console.log(1);
else
console.log(2);
});

或者如果你的html像这个

<input type="button" class="my_button" value="Test"/>
<input type="button" class="my_button" value="Test1"/>

然后使用这个脚本

$('.my_button').click(function() {
if($(this).val() ==="Test")
    console.log(1);
else
console.log(2);
});