Javascript使用事件动态创建元素

Javascript使用事件动态创建元素,javascript,jquery,html,web-applications,event-handling,Javascript,Jquery,Html,Web Applications,Event Handling,我正在尝试使用javascript和jQuery动态创建表单。表单有一些jQuery动画,这些动画是通过单击复选框输入元素触发的 以下是页面加载后(创建任何动态元素之前)的一些页面HTML: 对于第一个代码块中的静态部分,单击复选框时,一个div淡入,其下的另一个div滑入视图。我使用jQuery函数来实现这一点。对于静态创建的诗句,它完全按照预期工作。如果需要进一步解释,请告诉我 我想做的是在运行时通过JS复制这个部分,这样用户可以有更多这样的部分来填充。请参阅下面的代码,该代码创建此节的副本

我正在尝试使用javascript和jQuery动态创建表单。表单有一些jQuery动画,这些动画是通过单击复选框输入元素触发的

以下是页面加载后(创建任何动态元素之前)的一些页面HTML:

对于第一个代码块中的静态部分,单击复选框时,一个div淡入,其下的另一个div滑入视图。我使用jQuery函数来实现这一点。对于静态创建的诗句,它完全按照预期工作。如果需要进一步解释,请告诉我

我想做的是在运行时通过JS复制这个部分,这样用户可以有更多这样的部分来填充。请参阅下面的代码,该代码创建此节的副本并将其附加到父div(id=“escalationTimeout”):

如果我运行上述代码,将产生以下HTML块:

<div>
  <div class="div-formContainer" style="width: 195px;">
    <label title="tooltip text">
      <input type="checkbox" style="position: relative; top: 2px;"> checkbox text
    </label>
  </div>
  <div class="div-inline-block" style="display: none;">
    <input type="text" size="3" style="background-color: rgb(240, 248, 255);"> minutes
  </div>
  <div style="display: none;">
    Some other stuff here
  </div>
</div>
我也尝试了这个方法而不是上面的方法,但它不仅不起作用,而且还禁用了复选框:

newChildElement.addEventListener("click", cbtoggle(newChildElement));
newChildElement.addEventListener("click", slideUpDown(newChildElement));
谁能解释一下我哪里出了问题?提前感谢。

试试这个:

newChildElement.addEventListener("click", function(){
    cbtoggle(this);
    slideUpDown(this);
});
addEventListener
的回调函数不仅仅是要抛出的任何函数,它是一种使用
事件作为参数的特定类型。在这里,你不需要一个论点,但有时使用它很方便。例如,您可以看到这样的情况:

formElement.addEventListener('submit', function(e){
    // Prevent the normal behavious of submitting the form (aka loading the action target page)
    e.preventDefault();
});

这很有效,非常感谢。但是你能解释为什么这个能工作而这个不能吗?newChildElement.addEventListener(“点击”,cbtoggle(newChildElement));addEventListener(“单击”,slideUpDown(newChildElement));正如我所说,当您将函数名作为AddEventListener的参数时,它必须是一个处理事件的函数。请参见,当您将侦听器放在某个类型的事件上时,返回的
事件
对象将作为参数传递给回调函数。我邀请你阅读关于和
newChildElement.onClick = function() { 
                            cbtoggle(this); 
                            slideUpDown(this);
                           };
newChildElement.addEventListener("click", cbtoggle(newChildElement));
newChildElement.addEventListener("click", slideUpDown(newChildElement));
newChildElement.addEventListener("click", function(){
    cbtoggle(this);
    slideUpDown(this);
});
formElement.addEventListener('submit', function(e){
    // Prevent the normal behavious of submitting the form (aka loading the action target page)
    e.preventDefault();
});