Javascript/jQuery focusout event that changes layout causes click event to not fire

落花浮王杯 提交于 2019-12-06 07:18:15

问题


I have a field that when you leave focus on it, it changes the layout of the page. I also have buttons on the page that submit my form.

If I go into my field and type a value, then click the button, the button click event never fires. This seems to happen because the layout is changing before the click event gets fired, which means the button changes places. By the time the click event fires, it's firing on an empty area, not the button.

Here is a jsfiddle of the issue: http://jsfiddle.net/xM88p/

I figured out a way to solve this for IE but after extensive research I can't find/access the same object in FF/Chrome:

//only works in IE

if(event.originalEvent.toElement){
  $("#"+event.originalEvent.toElement.id).click();
}

回答1:


http://jsfiddle.net/xM88p/2/

Use mousedown instead of click:

$("#btn_test").on('mousedown', function (event){
    alert("clicked!"); 
});

$('#test').focusout(function (event){
    $('<p>Test</p>').insertAfter(this);
});

Edit

Okay, I got a little more creative with the event handlers. The new solution keeps track of mousedown/mouseup events as well as the position of the click. It uses these values to check whether mouse up should execute an alert.

var testClicked = false;
var lastX, lastY;

$(document).on('mouseup', function (event) {
    if (testClicked === true && lastX === event.clientX && lastY === event.clientY) {
        alert("clicked!"); 
    }
    testClicked = false;
    lastX = null;
    lastY = null;
});

$("#btn_test").on('mousedown', function (event){
    testClicked = true;
    lastX = event.clientX;
    lastY = event.clientY;
});

$('#test').focusout(function (event){
    $('<p>Test</p>').insertAfter(this);
});


来源:https://stackoverflow.com/questions/18339089/javascript-jquery-focusout-event-that-changes-layout-causes-click-event-to-not-f

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!