【问题标题】:button to create a new div which is already existing按钮创建一个已经存在的新 div
【发布时间】:2016-10-06 08:52:10
【问题描述】:
<form>    
<fieldset>
      <legend>DownTime</legend>
      <div id="downtime">
      Start of DownTime:
      <input type="time" name="startdowntime">
      Reason:
      <select type="text" name="reason">
      <option>Reason1</option>
      <option>Reason2</option>
      <option>Reason3</option>
      <option>Reason4</option>
      </select>
      End of DownTime:
      <input type="time" name="stoptdowntime">
      <br>
      </div>
      </br>
      <button type="button">Add another DownTime</button><br>
      </fieldset>
      <br>
      <fieldset>
</form>

我需要为我创建的按钮添加一个功能吗?使用按钮我想添加“n”个停机时间条目。

【问题讨论】:

  • 如果你这样做,你需要改变这个:&lt;div id="downtime"&gt; 这个:&lt;div class="downtime"&gt;。 ID 必须是唯一的,因此如果您需要创建多个实例,则不能以您正在做的方式使用 id。每次按下按钮时,您都可以使用 Jquery 克隆元素并将其附加到 dom。

标签: javascript jquery html css


【解决方案1】:
<form>    
<fieldset>
      <legend>DownTime</legend>
     <div id="parentdiv">
      <div class="downtime">
      Start of DownTime:
      <input type="time" name="startdowntime">
      Reason:
      <select type="text" name="reason">
      <option>Reason1</option>
      <option>Reason2</option>
      <option>Reason3</option>
      <option>Reason4</option>
      </select>
      End of DownTime:
      <input type="time" name="stoptdowntime">
      <br>
      </div>
      </br>
      </div>
      <button type="button" id="addbtn">Add another DownTime</button><br>

      <fieldset>
</form>

通过 Jquery 和 ES6:-

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

<script>
var html = `
   <div class="downtime">
          Start of DownTime:
          <input type="time" name="startdowntime">
          Reason:
          <select type="text" name="reason">
          <option>Reason1</option>
          <option>Reason2</option>
          <option>Reason3</option>
          <option>Reason4</option>
          </select>
          End of DownTime:
          <input type="time" name="stoptdowntime">
          <br>
          </div>
          </br>
`;
$("#addbtn").click(function(e){
    $("#parentdiv").append(html);
});

</script>

【讨论】:

  • 这将导致重复的ID's... ID 应该是唯一的,老实说,这是重新创建这些元素的糟糕方式。
  • 我已经在我的评论中指出了这个问题,你应该在发布答案之前先阅读所写的内容
  • 对不起..现在我已经编辑了我的答案..先生,如果这很糟糕,请指导正确的方式
  • @RajeshPatel 当我看到 OP 的尝试时我会的。我不只是扔掉免费的源代码。在我尝试进一步帮助他们之前,我希望看到那个人已经尝试并愿意帮助自己。学习的关键是尝试,而不是复制/粘贴,因为从 stackoverflow 获得答案的目的是向他们学习......我觉得最好等待编辑问题以显示相关信息。
  • @NewToJS 现在这是一个 "Crackford" 解决方案!
猜你喜欢
  • 1970-01-01
  • 2012-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多