按下按钮时,所选选项将消失


Selected option disappears when button is pressed

我有一个文件,template.php,其中包含一个JS函数,用于向页面添加一些下拉框选项,因此用户可以根据需要添加更多选项。我的问题是,如果用户在这些选择框中选择了某些选项,然后按"addsunday"按钮添加更多框,则先前选择的选项将被清除(因此页面上的每个下拉列表都会重置为 00:00)。我想知道是什么导致选择重置以及如何解决这个问题。

    $("#addsunday").click(function() {
        var htmlstring = "<div class='shiftwrapper'>";
        htmlstring += "<select data-col-id='start' form='newtemplateform'>";
        htmlstring += "<?php 
                            for($hours=0; $hours<24; $hours++) // the interval for hours is '1'
                                for($mins=0; $mins<60; $mins+=30) // the interval for mins is '30'
                                    echo '<option>'.str_pad($hours,2,'0',STR_PAD_LEFT).':'
                                                    .str_pad($mins,2,'0',STR_PAD_LEFT).'</option>';?>";
        htmlstring += "</select>"; 
        htmlstring += "<select data-col-id='finish' form='newtemplateform'>";
        htmlstring += "<?php 
                            for($hours=0; $hours<24; $hours++) // the interval for hours is '1'
                                for($mins=0; $mins<60; $mins+=30) // the interval for mins is '30'
                                    echo '<option>'.str_pad($hours,2,'0',STR_PAD_LEFT).':'
                                                    .str_pad($mins,2,'0',STR_PAD_LEFT).'</option>';?>";
        htmlstring += "</select>";
        htmlstring += "<select data-col-id='loc' form='newtemplateform'>";
        htmlstring += "<?php foreach($locations as $location){ print '<option value='"$location'">' . $location . '</option>'n'; }?>";
        htmlstring += "</select>";
        htmlstring += "<button class='removeshift'>Remove Shift</button><br/>";
        htmlstring += "</div>";
        document.getElementById('sundaywrap').innerHTML += htmlstring;
        console.log("Sunday clicked");
    });

如果这是一种非常低效的重复代码方式,我深表歉意,我仍在学习。这是一个非常糟糕的小提琴:https://jsfiddle.net/L7npxvzp/它不起作用,但是您可以看到下拉列表如何工作的结构。有一个按钮可以添加更多下拉列表,当按下此按钮时,以前更改的选择将重置回其默认值。

问题是这一行:

    document.getElementById('sundaywrap').innerHTML += htmlstring;

这会将#sundaywrap中的 DOM 元素替换为新的 DOM 元素,这些元素来自在连接 htmlstring 后解析 HTML。旧 DOM 元素中的任何动态状态(如菜单中的选定项)都将丢失。

与其连接到 HTML,不如附加到 DOM:

$("#sundaywrap").append(htmlstring);