当页面上具有相同选择器的多个按钮时,检查按钮单击的确切内容

时间:2015-03-05 08:29:59

标签: javascript jquery onclick

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

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

,然后点击按钮1两次,就像我点击两个按钮而不是单个按钮一样。所以我的问题是:JS中存在一些方法只能获取我点击的按钮,而不指定像id这样的唯一选择器。我是JS的新人,所以有人可以解释一下吗?我找到了相关问题here。谢谢!

编辑:

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

5 个答案:

答案 0 :(得分:2)

每个事件侦听器都会收到包含事件目标的事件。试试下面的例子。

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

答案 1 :(得分:1)

在功能代码中使用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
});

答案 2 :(得分:1)

试试这个:

<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/

答案 3 :(得分:0)

试试这个: -

<!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>

答案 4 :(得分:0)

如果您的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);
});