关于动态创建元素的Click事件的JQuery

时间:2016-02-21 13:49:32

标签: jquery

我在动态创建的元素上点击事件时遇到了JQuery问题。

动态创建的代码是:

<div class="container rounded">
   <div class="message_area" style="background-color: #dff0d8;border:1px solid #d6e9c6; color: #3c763d">
       <button class="close" type="button">x</button>
            Ya esta suscrito a nuestras listas de envío, sus datos han sido actualizados.
   </div>
</div>

当客户点击关闭按钮时,我正在尝试更改容器的高度(类bloqFormulario)。

我尝试过这些选项:

(function($){
    $(".close").click(function() {
        $(".bloqFormulario").height(200);   
    });
})(jQuery);



(function($){
    $(".message_area").on("click", "button", function() {
        $(".bloqFormulario").height(200);
    });
})(jQuery);

但我没有结果。

你能帮助我吗?

非常感谢。

2 个答案:

答案 0 :(得分:3)

像这样使用

$(function(){
    $(document).on("click",".close",function() {
         $('.bloqFormulario').css("height","200px");
    });
});

WORKING DEMO

答案 1 :(得分:0)

如果您使用的是jQuery 1.7+,那么您可以执行以下操作:

$('body').on('click', 'button.close', function() {
    $(".bloqFormulario").height(200); 
});

如果您使用的jQuery版本低于1.7,则需要在动态创建关闭按钮后注册click事件。当加载文档并且按钮甚至不存在时,在稍后将该按钮添加到文档后,您注册的jQuery onclick事件将无法工作,您必须在将按钮添加到文档后绑定click事件。 / p>

我会添加动态创建的代码,如下所示:

<div class="container rounded">
   <div class="message_area" style="background-color: #dff0d8;border:1px solid #d6e9c6; color: #3c763d">
       <button class="close" type="button">x</button>
            Ya esta suscrito a nuestras listas de envío, sus datos han sido actualizados.
   </div>
   <script type="text/javascript">
      $(".close").click(function() {
         $(".bloqFormulario").height(200);   
      });
   </script>
</div>

此处添加了代码,并且注册了单击偶数。

相关问题