Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/433.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用jquery检查按钮是否被单击_Javascript_Jquery_Html - Fatal编程技术网

Javascript 使用jquery检查按钮是否被单击

Javascript 使用jquery检查按钮是否被单击,javascript,jquery,html,Javascript,Jquery,Html,我正在尝试检查按钮是否被单击或未使用jquery 这是我代码中javascript部分的代码片段 window.onbeforeunload = function() { jQuery(':button').click(function () { if (this.id == 'click') { alert('this button was clicked'); } else if (this.id == 'button2') { al

我正在尝试检查按钮是否被单击或未使用jquery

这是我代码中javascript部分的代码片段

window.onbeforeunload = function() {

jQuery(':button').click(function () {
    if (this.id == 'click') {
        alert('this button was clicked');
    }
    else if (this.id == 'button2') {
        alert('Button 2 was clicked');
    }
});

};
这是我用来测试功能的按钮

<button id="click">save</button>
保存

单击按钮时,什么也不会发生。单击事件后,请协助您绑定事件。当onbeforeevent已激发时,单击已发生

您需要将其绑定到该事件之外

jQuery(function(){

    window.onbeforeunload = function() {
        console.log(clicked);
    };

    var clicked = null;
    jQuery('button').on("click", function () {
        clicked = this.id;
    });

});
请尝试以下方法:

jQuery(文档).ready(函数(){
jQuery(“:按钮”)。单击(函数(){
如果(this.id=='单击'){
警报(“已单击此按钮”);
}
else if(this.id==“button2”){
警报(“已单击按钮2”);
}
});
});

拯救

按钮2
按钮触发的事件在jQuery代码加载时给出,因此需要将其放入$(document.ready()中

这将对您有用:

$(document).ready(function(){
    $("#click").click(function(){
        //do stuff
    });
})
在这里,您可以直接寻址html所显示的按钮id:

<button id="click">save</button>
保存
实际上是一样的:D

var clickedButtons = [];
$('button').on('click', function(){
  if($.inArray($(this).attr('id'), clickedButtons){
    console.log('button allready clicked once');
  } else {
    clickdeButtons.push($(this).attr('id'));
  }
});

此解决方案可以处理多个按钮

jQuery('button')
,因此您在单击事件后将其绑定……为什么要在
onbeforeuload
中设置单击处理程序?当这个事件发生时,点击一个按钮不是很不可能吗?你到底想在这里完成什么?