我有两个具有相同选择器类的按钮。当我这样做时:
$('.my_button').click(function() {
console.log(1);
});
,然后点击按钮1
两次,就像我点击两个按钮而不是单个按钮一样。所以我的问题是:JS中存在一些方法只能获取我点击的按钮,而不指定像id
这样的唯一选择器。我是JS的新人,所以有人可以解释一下吗?我找到了相关问题here。谢谢!
编辑:
我使按钮有点不同。是的,它只返回单个按钮,但为什么单击触发器工作两次。控制台日志记录两次。
答案 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>
答案 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);
});