Chained method calls doesn't work on original nor cloned element, why?

前端 未结 2 1779
隐瞒了意图╮
隐瞒了意图╮ 2021-01-21 19:01

I have the following HTML:

    
         


        
2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-21 19:58

    The problem is that replaceWith returns the removed element, not the new element. I suggest a different path:

    $(function() {
      var cond1 = $('#condition_value_1');
      var cloned_cond1 = cond1.clone().removeAttr('style');
      var cond1_select = '';
    
      $('#showme').click(function() {
        cond1.replaceWith(cond1_select);
        $("#condition_value_1").select2({
          placeholder: 'Select choice'
        });
        cond1 = $("#condition_value_1");
      });
    
      $('#clickme').click(function() {
        if ($('#condition_value_1').hasClass('select2-hidden-accessible')) {
          $("#condition_value_1").select2('destroy');
        }
    
        $('#condition_value_1').replaceWith(cloned_cond1);
        cond1 = $('#condition_value_1');
      });
    });
    

    Note that I've removed the attribute from the clone before ever replacing anything; that way, you don't have to worry about it.

    Note also in the showme click handler, we replace the HTML, then get a new hook to $("#condition_value_1"). That's because cond1 is no longer in the DOM, since you've replaced it with the HTML in the first line.

    Likewise, in the clickme click handler, you need to reset the value of cond1 to match your new HTML.

提交回复
热议问题