当页面上有多个具有相同选择器的按钮时,请检查单击了哪个exatly按钮
Check what exatly button clicked, when multiple buttons with the same selector on page
我有两个具有相同选择器类的按钮。当我这样做时:
$('.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);
});
相关文章:
- Javascript/Ajax:通过点击按钮检查有效的电子邮件和电话号码
- html单选按钮检查问题
- JS中的单选按钮检查不起作用
- 更改单选按钮检查的值的字体大小
- Wooccommerce单选按钮检查jquery
- 通过单选按钮检查提交表单
- Backbone.js路由器和后退按钮检查
- 在检查单选按钮检查状态后启用/禁用表单元素
- 对用户交互进行单选按钮检查
- 单选按钮检查属性在函数 - JavaScript 中失败
- 基于单选按钮检查值调用Javascript函数
- 单选按钮检查的属性未更改
- jQuery单选按钮检查操作不'不要开火
- knockoutjs单选按钮检查了protectedobservable的值
- 通过单选按钮检查值
- 依靠单选按钮检查
- 我想通过输入类型按钮检查表单验证,而不是通过提交,任何人都可以帮助我
- 使用按钮检查两个或多个无线电组
- Angularjs:当模型改变时,单选按钮检查状态绑定模型值失败
- 条件Javascript重定向与后退按钮检查器