[英]How to use click event for anchor tag and button tag simultaneoulsy in jQuery?
I'm using jQuery 1.9.1 in my project. 我在我的项目中使用jQuery 1.9.1 。 I've following HTML : 我正在关注HTML:
<button type="button" id="btn_add" class="btn btn-primary">Add</button>
<a class="btn_delete" href="#"><i class="icon-trash"></i></a>
I want to display the same alert message if user clicks on a icon enclosed in anchor tag with class "btn_delete" or click on a button having id "btn_add". 如果用户单击锚标签中包含类“ btn_delete”的图标或单击具有id“ btn_add”的按钮,我想显示相同的警报消息。
For this I tried following code but it didn't work out for me. 为此,我尝试了以下代码,但对我而言没有用。
$(document).ready(function() {
$("button#btn_add.btn_delete").on("click", function(event) {
event.preventDefault();
alert("This action has been temporarily disabled!")
});
});
Can someone please help me in this regard please? 有人可以在这方面帮助我吗?
If you want any more information regarding the issue I'm facing please let me know. 如果您需要有关我所面临问题的更多信息,请告诉我。
Thanks in advance. 提前致谢。
**Approach #1**
function doSomething(){
//your code
}
$('#btn_add').click(doSomething);
$('.btn_delete').click(doSomething);
**Approach #2**
$("#btn_add,a.btn_delete").on("click", function(event) {
event.preventDefault();
alert("This action has been temporarily disabled!")
});
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("button#btn_add, a.btn_delete").on("click", function(event) {
event.preventDefault();
alert("This action has been temporarily disabled!")
});
});
</script>
Your code is quite close to what it should be. 您的代码非常接近应有的样子。 Change: 更改:
$("button#btn_add.btn_delete")
To: 至:
$("#btn_add,a.btn_delete")
You can use ,
to have multiple selectors. 您可以使用,
有多个选择。
$(".btn_delete i,#btn_add").on("click", function(event) {
event.preventDefault();
alert("This action has been temporarily disabled!")
});
You can have both the HTML Tag in the jQuery selector as below: 您可以在jQuery选择器中同时具有HTML标记,如下所示:
$(document).ready(function() {
$("button#btn_add, a.btn_delete").on("click", function(event) {
event.preventDefault();
alert("This action has been temporarily disabled!")
});
});
Hope this helps! 希望这可以帮助!
$(document).ready(function() {
$("#btn_add,.btn_delete").on("click", function(event) {
event.preventDefault();
alert("This action has been temporarily disabled!")
});
});
Additionally to the other answers: 除了其他答案:
Your current selector will find elements like this: 您当前的选择器将找到以下元素:
<button id="btn_add" class="btn_delete">Foo</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.