javascript - 按下按钮时所选选项消失

标签 javascript php jquery html

我有一个文件 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");

    });

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

最佳答案

问题出在这一行:

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

这会将 #sundaywrap 中的 DOM 元素替换为连接 htmlstring 后解析 HTML 所产生的新 DOM 元素。旧 DOM 元素中的任何动态状态(例如从菜单中选择的项目)都会丢失。

您应该附加到 DOM,而不是连接到 HTML:

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

关于javascript - 按下按钮时所选选项消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35758891/

相关文章:

javascript - jQuery Mobile 可折叠集 - 元素关闭时停止音频播放器

javascript - javascript中函数的间接引用

php - 从YouTube API批量下载图像

javascript - 如何检查一个单词在 Javascript 中的数组中出现的次数

php - session_start() 不起作用并发出警告,尽管它位于页面顶部

javascript - 按下后退按钮时,Ajax "POST"在 URL 中显示表单条目

javascript - 如何将类(class)应用于 child 有所需的两个类(class)的容器?

jquery选择器

javascript - 使用Meteor Spotify API根据单词搜索返回专辑列表,需要为列表中的每个专辑拉入轨道

javascript - 如何设置一个字段等于postId [METEOR]