单击某个地方时添加事件

Add event when click at some place

我正在开发一个简单的管理系统。现在我想让管理员更容易编辑数据。我的目标是,当一个元素被双击时,它会变成输入。然后在编辑之后,如果管理员在输入之外单击,它 运行 是 运行 ajax 的一个事件。就像PHPMyAdmin中的系统一样,当我们要编辑数据时,只需双击数据即可。

HTML

<tbody>
    <tr>
        <th scope="row">1</th>
        <td class="editable" name="email">myname@myweb.com</td>
        <td class="editable" name="username">this_is_username</td>
        <td class="editable" name="name">My Name</td>
    </tr>
</tbody>

JavaScript

$(".editable").dblclick(function () {
    const id = $(this).data("id");
    const col = $(this).attr("name");
    $(this).html(
        "<form>
             <input class="editing" type='text' value='" + $(this).val() + "'>
        </form>"
    );
});

// I want this Ajax will execute whene other side is clicked

$.ajax({
        url: "http://localhost/myProject/myController/myMethod",
        type: "post",
        data: {
            id: id,
            col: col,
            value: $('.editing').val()
        },
        success: function () {
            document.location.href = "http://localhost/myProject/myController";
        },
    });

控制器

public function myMethod()
{
    $id = $this->input->post("id");
    $col = $this->input->post("col");
    $value = $this->input->post("value");
    $this->db->set($col, $val);
    $this->db->where('id', $id);
    $this->db->update("my_table");
}

但我不知道如何在管理员单击输入之外时执行 Ajax 事件。任何人都可以帮助我吗?或者已经做了什么功能?

***注意:我想在标签锚上排除它。所以,当某些link被按下时,它不会执行Ajax,而是转到link。

使用输入元素的onblur事件。当用户将焦点从输入字段移出时它会触发。

由于您使用的是 jQuery,请勾选模糊事件,如下所示:

    $(".editable").dblclick(function () {
        const id = $(this).data("id");
        const col = $(this).attr("name");
        $(this).html(
            "<form>
                 <input class="editing" type='text' value='" + $(this).val() + "'>
            </form>"
        );
        
        // use more specific targets here, i just use the class of the input
// you should use the same $(this) content in the end
        $('.editing').blur(function() {
            $.ajax({
                url: "http://localhost/myProject/myController/myMethod",
                type: "post",
                data: {
                    id: id,
                    col: col,
                    value: $('.editing').val()
                },
                success: function () {
                    document.location.href = "http://localhost/myProject/myController";
                },
            });
        });
        
    });

blur 事件在附加到它的元素失去焦点时触发,但不会通过冒泡触发,仅针对特定元素。

查找 blur or maybe focusOut

的更多信息