javascript - 如何检测元素的点击

标签 javascript jquery

基本上,我希望用户点击任何 .editable 项目,这会使输入出现,复制其样式,然后如果他们点击其他任何地方,我希望输入消失并保存更改。我很难完成这项工作。我见过 solution使用 event.stopPropagation,但我不知道如何按照我的代码结构方式包含它:

$(function() {
    var editObj = 0;
    var editing = false;   

    $("html").not(editObj).click(function(){
         if (editing){
                $(editObj).removeAttr("style");
                $("#textEdit").hide();
                alert("save changes");
            }
    });    


    $(".editable").not("video, img, textarea")
        .click(function(event) {

            editObj = this;
            editing = true;

            $("#textEdit")
                .copyCSS(this)
                .offset($(this).offset())
                .css("display", "block")
                .val($(this).text())
                .select();

            $(this).css("color", "transparent");


    });
}

copyCSS 函数来自 here

我需要区分对可编辑对象的点击和远离它的点击,即使该点击是针对不同的可编辑对象(在这种情况下它应该调用 2 个事件)。

最佳答案

试试这个:

$('body').click(function(event) {
    var parents = $(event.target).parents().andSelf();
    if (parents.filter(function(i,elem) { return $(elem).is('#textEdit'); }).length == 0) {
        // click was not on #textEdit or any of its childs
    }
});

$(".editable").not("video, img, textarea")
        .click(function(event) {

    // you need to add this, else the event will propagate to the body and close
    e.preventDefault();

http://jsfiddle.net/dDFNM/1/

这通过检查被点击的元素或其任何父元素是否为#textEdit 来工作。

event.stopPropagation 解决方案可以这样实现:

// any click event triggered on #textEdit or any of its childs
// will not propagate to the body

$("#textEdit").click(function(event) {
    event.stopPropagation();
});

// any click event that propagates to the body will close the #textEdit

$('body').click(function(event) {
    if (editing) {
        $("#textEdit").hide();
    }
});

http://jsfiddle.net/dDFNM/2/

关于javascript - 如何检测元素的点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7126191/

相关文章:

javascript - 如果为空则隐藏引导警报不起作用

javascript - Backbone Marionette 目标元素在 el 与 jQuery

jquery - 单击按钮或链接打开 Drop Drown Like Google

javascript - 带有 Colorbox 插件的简单 jQuery 图片库的问题

javascript - 使用 ionic 框架在 sqliteDB 中插入一条记录

javascript - 如何更改单击时的下拉列表标签文本?

c# - 如何使按钮不显示但仍被javascript使用?

javascript - jQuery 3.2.1,自动数字插件(最新) 'Uncaught SyntaxError: Unexpected token export'

javascript - three.js 在线包含它的 URL 是什么?

javascript - jQuery/JavaScript : Avoid unique ID's for each row in a table?