[英]test whether button being clicked before running function on element.blur()
I have a function called showHide() that alternately shows and hides a text input field and a button (button2) when another button (button1) is clicked. 我有一个名为showHide()的函数,当单击另一个按钮(button1)时,该函数交替显示和隐藏文本输入字段和一个按钮(button2)。 The text input field is automatically focused when it opens, and this works great. 文本输入字段在打开时会自动聚焦,效果很好。
The HTML looks roughly thus: HTML大致如下所示:
<button1>Show/Hide</button>
<form>
<input class="hidden" type="text" />
<button2 type="submit">Submit</button>
</form>
<script type="text/javascript">
$("button1.someSelectors").click(function() {showHide();});
$("input.someSelectors").blur(function() {showHide();})
</script>
I would like to extend the function such that when the input field loses focus it and button1 disappear, unless it loses focus because button1 is being clicked. 我想扩展该函数,以便当输入字段失去焦点时,按钮1消失, 除非因为单击button1而失去焦点。 As it reads now I'm only testing whether the input field has focus or not. 正如现在所读,我仅测试输入字段是否具有焦点。 How can I also check whether button2 is being clicked or not? 如何查看按钮2是否被单击?
I tried: 我试过了:
$("input.someSelectors").blur(function() {
if (!$("button2.someSelectors").is(":focus")) {
showHide();
}
});
but it hid the form elements even when I tried clicking button2. 但即使我尝试单击button2,它也隐藏了表单元素。
An alternative would be to test whether button2 is being clicked or not in the "hide" part of the function, but when I added 一种替代方法是测试是否在函数的“隐藏”部分中单击了button2,但是当我添加时
if(!$("button2.someSelectors").click()) {do the hide part of the function}
to showHide(), the form got submitted when I clicked button1 or button2. 到showHide(),当我单击button1 或 button2时就提交了表单。 Here is an example of my problem. 这是我的问题的一个例子 。 Can anyone help? 有人可以帮忙吗?
-- Edit: - 编辑:
var showHide=function(item, category) {
if($("input."+item+"."+category).hasClass("hidden")) {
$("input."+item+"."+category).show("fast").focus().removeClass("hidden");
$("button.buy."+item+"."+category).show("fast");
$("button.purchase."+item+"."+category).text("Never mind!");
} else {
$("input."+item).hide("fast").addClass("hidden");
$("button.buy."+item).hide("fast");
$("button.purchase."+item).text("Purchase");
}
}
blur
event on textbox
is triggered before the click
event fires on the button. 在click
事件触发按钮之前,将触发textbox
上的blur
事件。 In order to avoid that you can use mousedown
event instead of click
event which will be triggered before click
event. 为了避免这种情况,您可以使用mousedown
事件代替click
事件,而click
事件将在click
事件之前触发。 Try this 尝试这个
$("button1.someSelectors").mousedown(function() {showHide();});
$("input.someSelectors").blur(function() {showHide();})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.