我有一个类似于下面的按钮
<button id="uniqueId" onclick="runMethod(this)">Submit</button>
我想做的是停止运行runMethod,直到完成自己的检查为止。我试过使用该stopImmediatePropagation
函数,但这似乎没有用。这是我的jQuery:
$j(document).on('click', '#uniqueId', function(event) {
event.stopImmediatePropagation();
if(condition == true) {
// continue...
} else {
return false;
}
return false;
});
注意:runMethod
基本上验证表单,然后触发提交。
您想做的事情,尤其是您想做的事情,需要某种变通的解决方法,但总会有些麻烦。最好更改按钮的行为方式(例如,处理jQueryclick()
函数内部的整个click事件或类似行为的东西)。但是,基于您的用户首先将鼠标悬停在按钮上的假设,我发现了针对您的问题的某种解决方案。我确定您可以将该功能扩展到键盘的Tab
事件,但是对于移动设备的触摸输入来说,可能无法完美使用。因此,请记住以下解决方案是针对您问题的半完全解决方法:
$(document).ready(function(){
var methodToRun = "runMethod(this)"; // Store the value of the onclick attribute of your button.
var condition = false; // Suppose it is enabled at first.
$('#uniqueId').attr('onclick',null);
$('#uniqueId').hover(function(){
// Check your stuff here
condition = !condition; // This will change to both true and false as your hover in and out of the button.
console.log(condition); // Log the condition's value.
if(condition == true){
$('#uniqueId').attr('onclick',methodToRun); // Enable the button's event before the click.
}
},
function(){
console.log('inactive'); // When you stop hovering over the button, it will log this.
$('#uniqueId').attr('onclick',null); // Disable the on click event.
});
});
它的作用是使用hover
事件触发您的检查逻辑,并且当用户最终单击按钮时,如果逻辑正确,则启用该按钮,否则它将不执行任何操作。试试这个小提琴吧。
PS:转换$
到$j
需要适应这一点。
PS2:使用Javascript控制台检查小提琴的工作方式,因为它本身不会更改页面上的任何内容。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句