【问题标题】:When using Jquery append(), the div which is appending, isn't able to reach使用 Jquery append() 时,追加的 div 无法到达
【发布时间】:2014-10-09 04:37:05
【问题描述】:

每次用户单击“添加”按钮时,我都会使用 Jquery 的附加功能来创建一个新的输入字段。连同输入字段,我想在表单中放置一个 div 类“删除”。

因此,如果用户单击加号,则必须显示新的输入字段。当他在 MIN 上单击该输入字段时,必须删除该字段。

http://jsfiddle.net/hg1zdc8p/1/

$( document ).ready(function() {
    $('#plus2').click(function() {
    $("#link2").append('<p><input type="text" class="form-control extralink" name="websitepartner[]"><span id="plus2" class="glyphicon glyphicon-minus minus">MIN</span></p>');    
    });

    $('.minus').click(function() {
        $(this).parent('p').remove();
    });
});

我做错了什么?

谢谢!

【问题讨论】:

    标签: jquery input append


    【解决方案1】:

    你应该使用 .on() 方法来访问附加的元素。它应该可以正常工作:

     $( document ).ready(function() {
        $('#plus2').click(function() {
        $("#link2").append('<p><input type="text" class="form-control extralink" name="websitepartner[]"><span id="plus2" class="glyphicon glyphicon-minus minus">MIN</span></p>');    
        });
    
        $(document).on('click','.minus',function() {
            $(this).parent('p').remove();
        });
    });
    

    http://jsfiddle.net/hg1zdc8p/2/

    【讨论】:

      【解决方案2】:

      事件处理程序仅绑定到当前选定的元素;在您的代码进行事件绑定调用时,它们必须存在于页面上。

      当您动态创建元素时。

      您需要使用Event Delegation。您必须使用委托事件方法使用.on()

      委托事件的优点是它们可以处理来自后代元素的事件,这些事件会在以后添加到文档中。

      一般语法

      $(document).on(event, selector, eventHandler);
      

      你的情况

       $("#link2").on('click', '.minus', function () {
           $(this).parent('p').remove();
       });
      

      DEMO

      【讨论】:

        【解决方案3】:

        您正在将事件附加到在 DOM 初始化期间不存在的元素。要将事件附加到动态元素,请使用以下符号:

        $("parent-element").on("click", "child-element", function(){});
        

        Fiddle 的更新版本:http://jsfiddle.net/hg1zdc8p/4/

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-08-03
          • 2014-12-31
          • 2016-08-17
          • 1970-01-01
          • 2011-04-04
          • 2013-03-02
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多