【问题标题】:Why is my .empty() not emptying the parent element?为什么我的 .empty() 没有清空父元素?
【发布时间】:2021-12-14 21:23:35
【问题描述】:

我无法让 jQuery 空方法处理我附加的 HTML 元素。 这是一个看似很简单的问题,但它让我打败了。

我尝试在代码中移动 empty 方法,但仍然无法将其清空。

编辑:除非有更多文本,否则我不会编辑它,所以这里有更多文本。

我的 jQuery/JavaScript:

// Declares blank arrays
let monthHolidayName = [];
let monthHolidayDescription = [];
let monthHolidayDay = [];
let monthHolidayMonth = [];
let monthHolidayIsoDate = [];
              
// On change pushes the arrays with the current months data
$('#monthSelect').change(function(){
          
  var selectedMonth = $('#monthSelect').val();
  var numSelectedMonth = parseInt(selectedMonth) + 1;

  for(i = 0; i < result['data']['holidays'].length; i++){
    var holidayMonth = result['data']['holidays'][i]['date']['datetime']['month'];
    if(holidayMonth === numSelectedMonth){
      // console.log((result['data']['holidays'][i]));
      monthHolidayName.push(result['data']['holidays'][i]['name']);
      monthHolidayDescription.push(result['data']['holidays'][i]['description']);
      monthHolidayDay.push(result['data']['holidays'][i]['date']['datetime']['day']);
      monthHolidayMonth.push(result['data']['holidays'][i]['date']['datetime']['month']);
      monthHolidayIsoDate.push(result['data']['holidays'][i]['date']['iso']);
    }
  }

  // Empties the #holidays element <--------------------
  $("#holidays").empty();
  
  // Appends the data to the modal
  for(i = 0; i < monthHolidayName.length; i++){
    var holidayName = monthHolidayName[i];
    var holidayDescription = monthHolidayDescription[i];
    var holidayDay = monthHolidayDay[i];
    var holidayDayMonth = monthHolidayMonth[i];
    var holidayIsoDate = monthHolidayIsoDate[i];

    var dateParsed = Date.parse(`${holidayDay} ${holidayDayMonth}`).toString("MMMM dS");
    // Appends elements to #holidays with the data         
    $("#holidays").append(`<div class="list-group-item list-group-item-action"><div style="text-decoration: underline; text-align: center;">${holidayName}</div><div style="text-align: center">${holidayDescription}</div><small class="text-muted">${holidayIsoDate}</small></div>`);
  }          
});

我的 HTML 代码:

 <!-- Calendar Modal -->
<div class="container">
  <div class="row">
    <div class="col-md-12">
        <div class="modal fade " id="calendar-modal">
          <div class="modal-dialog">
            <div class="modal-content">
               
              <div class="modal-header"> 
                  <h1 id="modalTitle">Holidays</h1>
                  <button type="button" class="close btn btn-secondary" data-bs-dismiss="modal" >&times;</button>
              </div>
              <!-- This is the body section of our modal overlay --> 
               <div class="modal-body" id="modalBody">
                <div class="btn-group dropright">
                  <select class="form-select form-select-sm mb-3" id="monthSelect"> 

                  </select>
                </div>
                <div class="list-group">
                  <button type="button" class="list-group-item list-group-item-action active" id="holidayTitle">
                    Holidays in <span id="currentMonth"></span>
                  </button>
                  <span id="holidays">
                  </span>
                  
                </div>               
              </div>
               <!-- This is the footer section of our modal overlay  -->
              <div class="modal-footer">
                  <button type="button" class="btn btn-secondary" data-bs-dismiss="modal" >Close</button>
              </div>
            </div>
          </div>
        </div>
     </div>
  </div>
</div> 

【问题讨论】:

  • 为什么要使用这么多不同的数组?如果您使用单个对象数组,事情会容易得多。
  • 请输入您的 HTML 代码。
  • 您永远不会清空数组。因此,每次更改选择时,都会将所有新月份的假期添加到数组中。然后将它们全部放入#holidays
  • .empty() 可以正常工作。如果您注释掉附加到它的循环,您会看到。
  • 我的 HTML 代码已添加。

标签: javascript html jquery json


【解决方案1】:

您似乎既想将append 新数据添加到现有数据,又想删除旧数据。您的代码一直在引用append,这意味着您要保留以前的数据,但您的问题是如何清除holidays div,然后添加新的假期。

回答您的问题,如果我们总是删除以前的假期信息,我们不需要数组,而是可以使用JavaScript Object 来保存信息。您会注意到我更改的另一部分是我取出了您拥有的for loop。由于我们有一个 single 假期,因此我们不需要遍历数组。以下代码应显示如何处理对象中的单个假期。请注意,我没有更改 HTML

// Declare an object with our empty parameters:
let holiday = {
  name: "",
  description: "",
  day: "",
  month: "",
  isoDate: ""
};
          
// On change pushes the arrays with the current months data
$('#monthSelect').change(function(){
      
  var selectedMonth = $('#monthSelect').val();
  var numSelectedMonth = parseInt(selectedMonth) + 1;

  for(i = 0; i < result['data']['holidays'].length; i++){
    var holidayMonth = result['data']['holidays'][i]['date']['datetime']['month'];
    if(holidayMonth === numSelectedMonth){
      // console.log((result['data']['holidays'][i]));

      // Using object setter notation to change each key:
      holiday.name = result['data']['holidays'][i]['name'];
      holiday.description = result['data']['holidays'][i]['description'];
      holiday.day = result['data']['holidays'][i]['date']['datetime']['day'];
      holiday.month = result['data']['holidays'][i]['date']['datetime']['month'];
      holiday.isoDate = result['data']['holidays'][i]['date']['iso'];
    }
  }

  // Empties the #holidays element <--------------------
  $("#holidays").empty();

  var dateParsed = Date.parse(`${holiday.day} ${holiday.month}`).toString("MMMM dS");
  // Appends elements to #holidays with the data         
  $("#holidays").append(`<div class="list-group-item list-group-item-action"><div style="text-decoration: underline; text-align: center;">${holiday.name}</div><div style="text-align: center">${holiday.description}</div><small class="text-muted">${holiday.isoDate}</small></div>`);
});

【讨论】:

    【解决方案2】:

    你可以管理这个

       $("#yourDiv").html(""); // jQuery
    

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    • 请注意,这在这种情况下可能不起作用,因为@HJP 会立即将元素重新附加到 div 中
    猜你喜欢
    • 2018-05-14
    • 1970-01-01
    • 2022-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-01
    相关资源
    最近更新 更多