清除元素的html而不是附加到该元素

时间:2018-04-05 15:01:16

标签: javascript jquery

我有一个循环的对象,如下所示:

rules: Array(3), valid: false, condition: "AND"}
condition:"AND"
rules:Array(3)

0:field:"ImpressionShare"
id:"ImpressionShare"
operator:"greater_calculation"
type:"integer"
value:{target: "0.5", operator: "x", inputValue: "AdGroupType"}

Object
1:field:"AggregatedFields.ROIIncludingAssisted"
id:"AggregatedFields.ROIIncludingAssisted"
operator:"not_begins_with"
type:"string"
value:[]

2:field:"Impressions"
id:"Impressions"
operator:"less_or_equal_calculation"
type:"integer"
value:{target: "0.5", operator: "x", inputValue: "AdGroupType"}

我遍历规则,而不是通过我想要根据值创建输入的值,并将它们添加到这样:

loadedRules.rules.forEach( function(item, index){
   var value = item.value;

   for(var i in value){

      var inputs = document.createElement("input");
      inputs.className = "form-control";

      console.log(inputs);
      console.log(value[i]);

      $(inputs).val(value[i]);

        $(`#builder-widgets_rule_${index}`).find('.rule-value-container').html('')
      $(`#builder-widgets_rule_${index}`).find('.rule-value-container').append(inputs);
   }


   console.log($(`.builder-widgets_rule_${index}`).find('.rule-value-container'));
})

但它只附加一个元素,如果我不用html('')清除它,那么它会将它们全部附加,但我想先清除它而不是追加

1 个答案:

答案 0 :(得分:0)

很简单:在.html('')循环之前使用for清除元素。这样您就不会在for循环的每次迭代中最终清除内容:

loadedRules.rules.forEach( function(item, index){
   var value = item.value;

   // Clear everything first
   $(`#builder-widgets_rule_${index}`).find('.rule-value-container').html('')

   for(var i in value){

      var inputs = document.createElement("input");
      inputs.className = "form-control";

      $(inputs).val(value[i]);

      // Append iteratively
      $(`#builder-widgets_rule_${index}`).find('.rule-value-container').append(inputs);
   }
});

或者,您甚至不需要依赖document.createElement来创建输入,jQuery可以很好地处理它:

loadedRules.rules.forEach( function(item, index){
   var value = item.value;

   // Clear everything first
   $(`#builder-widgets_rule_${index}`).find('.rule-value-container').html('');

   $.each(item.value, function(i, itemValue) {
     // Create new input element
     var $input = $('input', {
        'class': 'form-control'
     }).val(itemValue);

     // Append created input element
     $(`#builder-widgets_rule_${index}`).find('.rule-value-container').append($input);
   });
})