简体   繁体   English

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

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

Whenever I click on an image, a modal box should pop up with an appended paragraph once. 每当我单击图像时,模态框都会弹出一次,并带有一个附加段落。 I have two issues. 我有两个问题。 Firstly, my header text doesn't append to the header element. 首先,我的标题文本不会追加到header元素。 Secondly, it keeps appending the same paragraph into the modal box every time I click the laptop. 其次,每次我单击笔记本电脑时,它始终将相同的段落添加到模式框中。

HTML 的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 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');
});

Here's my JSFiddle if that description wasn't clear. 如果描述不清楚,这是我的JSFiddle

I'm not sure as how to temporarily remove the paragraph when you close the box. 我不确定关闭框时如何暂时删除该段落。 I tried .remove() but when the laptop is clicked, the paragraph is removed completely (well no duh). 我尝试了.remove(),但是当单击笔记本电脑时,该段落被完全删除了(不会吧)。 .detach() doesn't work either. .detach()也不起作用。

If I'm understanding the desired behavior correctly, then I believe you are looking for .empty() 如果我正确理解了所需的行为,那么我相信您正在寻找.empty()

In your close modal callback, try adding: 在关闭的模式回调中,尝试添加:

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

Change modal box onclick to this: 将模式框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");
  });

And empty should be in open modal. 空应该处于开放模式。 Otherwise if modal still open on click will add additional paragraph 否则,如果在点击时仍然打开模态,则会添加其他段落

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM