onclick在onclick使用的另一个元素中的元素上

onclick on element that is inside other that is used by onclick too

本文关键字:元素 onclick 另一个      更新时间:2023-09-26

这里有这样的问题,但我尝试了解决方案,在我的情况下,这不起作用。我有一个通过点击打开的表单,然后必须通过点击该表单内的x关闭它。这个变体不适合,因为cookie在关闭表单后没有设置为on。如果我打开,请将其设置为关闭单击。这也不起作用,因为单击x调用所有形式的单击事件。如果我真的喜欢解决方案,我会发现在stackoverflow中,表单根本不会打开。这是我的js代码:

$(document).ready(function () {
    if ($.cookie('techSupport') == null) {
        $.cookie('techSupport', 'off');
    } else if ($.cookie('techSupport') == 'on') {
        $.cookie('techSupport', 'off');
    };
}).on("click", "div#techSupport", function (event) {
    if ($.cookie("techSupport") == 'off') {
        $.cookie("techSupport", "on");
        var res = "<nobr><div>Technical support<a href='#' id='closeChat'>x</a></div></nobr>'n" +
            "<div id='chatBox'>What's your probloem?</div>'n" +
            "<textarea id='messageBox'></textarea>'n" +
            "<button id='sendToSupport'>Send</button>";
        $(this).css("width", "200px");
        $(this).css("height", "400px");
        $(this).html(res);
    }
}).on("click", "div#techSupport,a#closeChat", function () {
    var res = "<div id='techSupport'>techsupport</div>";
    $("div#techSupport").html(res);
    $("div#techSupport").css("width", "100px");
    $("div#techSupport").css("height", "10px");
    console.log($("div#techSupport").html());
    $.cookie("techSupport","off");
    event.stopPropagation();
    //window.location.reload();
});

HTML:

<div id="techSupport">techsupport</div>

那么,我如何可以忽略主窗体点击交叉?

这里有两个选项,停止事件在a#closeChatonclick中的传播(注意,我还在处理程序中添加了e参数):

.on("click", "a#closeChat", function (e) {
    var res = "<div id='techSupport'>techsupport</div>";
    $("div#techSupport").html(res);
    $("div#techSupport").css("width", "100px");
    $("div#techSupport").css("height", "10px");
    console.log($("div#techSupport").html());
    $.cookie("techSupport","off");
    e.stopPropagation();
    //window.location.reload();
});

http://jsfiddle.net/d6fpfzsu/10/

检查div#techSupport处理程序上eventtarget属性:

if ($.cookie("techSupport") == 'off' && event.target.id != 'closeChat') {
    $.cookie("techSupport", "on");
    var res = "<nobr><div>Technical support<a href='#' id='closeChat'>x</a></div></nobr>'n" +
        "<div id='chatBox'>What's your probloem?</div>'n" +
        "<textarea id='messageBox'></textarea>'n" +
        "<button id='sendToSupport'>Send</button>";
    $(this).css("width", "200px");
    $(this).css("height", "400px");
    $(this).html(res);
}

http://jsfiddle.net/d6fpfzsu/11/

最佳解决方案将取决于每个用例。