jQuery - Focus out on TR

天涯浪子 提交于 2019-12-04 07:03:24

I would handle your request by binding a click handler for the whole document, and then adding a stopPropagation() call within my other click events. I've setup a fiddle to demonstrate: http://jsfiddle.net/NwftK/

<table border="1" width="200">
    <tr id="myRow"><td>Hello</td><td>World</td></tr>
</table>

And the jQuery:

$(function () {
    $("#myRow").on('click', function (e) {
       $(this).css('background-color', 'blue');
        e.stopPropagation();
    }); 

    $(document).on('click', function () {

       $("#myRow").css('background-color', 'red');
    });

});

The problem is that even if you have nested elements, focusout will trigger on the parent element when you focus on one of the child elements. A solution I can think of would be to keep track of the current row using a variable. The pseudo code might work something like this:

var row = '';
$(table_element).click(function() { 
                           focused_row = $(this).parent();
                           if(row != '' && focused_row != row) {
                               //code to save edits, user clicked different row
                           }
                           row = focused_row;
                       });

There are 2 cases where you need to detect when the row loses focus, One while you are inside the table and two when you leave the table.

You can try something like this:

//store the last visited row
var row = false;

// save the row if has changed
function save () {
    if (row.changed){
        console.log("save");
    }
}

// keep track of the row you are in
// it doesnt work when you leave the table
$("tr").on("focusin", function (e) {
    if (row != this){
        if (row){
            save();
        }
        row = this;
        e.stopPropagation();
    }
});

//keep track whenever the row changes
$("tr").on("change", function (e) {
    this.changed = true;
    console.log("changed");
})

//triggers when you leave the table, you can try to save changes then.
$(document).on("focusin", function (e) {
    var el = $(e.target); //input or element that triggers this event
    var elrow = el.parent().parent()[0]; // try to get the row from that input, ... if its an input
    if (row && row !=elrow) {
        save();
        e.stopPropagation();
    };
})
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!