簡體   English   中英

如何防止在jQuery的BS模式div中多次附加html?

[英]How do you prevent appending html multiple times in BS modal divs in jQuery?

每當我單擊圖像時,模態框都會彈出一次,並帶有一個附加段落。 我有兩個問題。 首先,我的標題文本不會追加到header元素。 其次,每次我單擊筆記本電腦時,它始終將相同的段落添加到模式框中。

的HTML

<!--Trigger Image -->
<img src="https://cdn2.iconfinder.com/data/icons/pittogrammi/142/02-512.png" id="laptop" class="openmodal">

<!--Modal Box -->
<div class="question" id="question-modal">
  <header id="modal-header">
    <a href="#" class="close">X</a>
  </header>
  <div class="answer">
  </div>
</div>

JS

var id = this.id;

//Open the modal box
$('.openmodal').on('click', function() {
  $('#question-modal').modal('show');
  if (id == 'laptop')
    $('header').append('<h3>FAQs on laptops</h3>');
    $('.answer').append("Mac > any PC");
});

//close modal box
$('.close').on('click', function() {
  $('#question-modal').modal('hide');
});

如果描述不清楚,這是我的JSFiddle

我不確定關閉框時如何暫時刪除該段落。 我嘗試了.remove(),但是當單擊筆記本電腦時,該段落被完全刪除了(不會吧)。 .detach()也不起作用。

如果我正確理解了所需的行為,那么我相信您正在尋找.empty()

在關閉的模式回調中,嘗試添加:

$('.answer').empty();

將模式框onclick更改為此:

//Open the modal box
$('.openmodal').on('click', function() {
    $('#question-modal').modal('show');
    if (this.id == 'laptop')
    $('header'). append('<h3>FAQs on laptops</h3>');
    $('.answer').empty();
    $('.answer').append("Mac > any PC");
  });

空應該處於開放模式。 否則,如果在點擊時仍然打開模態,則會添加其他段落

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM