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

Method calling twice on second run - JavaScript

本文关键字:第二次 运行 JavaScript 两次 调用 方法      更新时间:2023-09-26

我在做什么:所以,我在这个网页上使用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");
    }
});

你可以在这里看到一个工作的例子。

繁殖:
1. 打开下拉菜单
2. 点击"新",
3.输入一些东西并按"enter",然后重复步骤1和2。

您实际上复制了整个<body>,包括脚本,这就是事件相乘的原因。

代替:

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

使用如下方法 append :

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

虽然上面也不是一个很好的主意,我强烈建议你设置一个主容器<div id="container">元素在body和修改你的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