方法在第二个 运行 - JavaScript 上调用两次

Method calling twice on second run - JavaScript

我在做什么:因此,我在此网页中使用 jQuery、Bootstrap 和 Font Awesome。这将创建一个用于输入的文本框,当用户完成输入并按下 'enter' 时,该项目将添加到清单中。

有什么问题:当我将第一项添加到检查列表时,它工作正常。但是当我尝试添加下一个时,它显示了两个输入框,一个在正确的位置,一个在左上角

/* Defining Variables */   
var toggled = false;
var thing = "";
var inMethod = false;

/* Defining Methods */
$(document).on("click", "#toggle", function() {
    if($(this).attr("class") == "fa fa-check-square-o fa-5x checked") {
        $(this).attr("class", "fa fa-square-o fa-5x unchecked");
    }
    else {
        $(this).attr("class", "fa fa-check-square-o fa-5x checked");
    }
    console.log();
});
function newThing() {
        $("body").html($("body").html() + "<div id='input'><div class='input-group margin-bottom-sm' id='imad'><span class='input-group-addon'><i class='fa fa-file-text-o fa-1x'></i></span><input id='myInput' class='form-control' type='text' placeholder='Input'></div></div>");
        inMethod = true;
        console.log(inMethod);
        var box = $("#input");
        var ema = $("#imad");

        box.css("top", screen.height / 2 - 175);
        box.css("left", screen.width / 2 - 175);

        ema.css("top", screen.height / 64);
        ema.css("left", screen.width / 64);
}
window.addEventListener("keydown", function(e){
    if(e.keyCode == 13 && inMethod) {
        thing = $("#myInput").val();
        $("#checklist").html( $("#checklist").html() + "<div id='checkOption'><i id='toggle' class='fa fa-square-o fa-5x unchecked'></i><span id='ds' class='fa fa-4x'>" + thing + "</span></div>" );
        window.location.hash = "";
        inMethod = false;
        console.log(inMethod);
        $("#input").remove();
    }
});
$(window).on('hashchange', function() {
    if(window.location.hash.substr(1) == "new") {
        inMethod = false;
        newThing();
    } else if(window.location.hash.substr(1) == "clear") {
        $("#checklist").html("");
    } else if(window.location.hash.substr(1) == "delete") {
        alert("Disabled for now");
    }
});

您可以查看此工作的示例 here

转载:
1. 打开下拉菜单
2. 点击'New',
3. 输入内容并按 'enter' 然后重复步骤 1 和 2。

您实际上是在复制整个 <body>,包括脚本,这就是事件成倍增加的原因。

而不是:

$("body").html($("body").html() + "...

使用类似append的方法:

$("body").append("...

虽然以上也不是一个好主意,但我强烈建议您在 body 中设置一个主容器 <div id="container"> 元素并在其中修改您的 HTML ,而无需影响 javascript 个标签。

<body>

    <div id="container">
        All contents goes here
    </div>

    <script type="text/javascript">
        // ...
        function newThing(){
            $("#container").append("...");
            // ...
        }
        // ...
    </script>

</body>

您需要使用 .append()。现在,您正在呈现输入框,但默认情况下,样式会将元素插入页面的左上角。这是更新后的 plunkr http://plnkr.co/edit/qrFOomKQrfZP3r4FmriC?p=preview