如何在点击时添加和删除GIF?

时间:2017-09-16 16:33:03

标签: javascript jquery html materialize

我正在使用materialize在我的页面上创建可折叠的手风琴。我想在点击可折叠标题时将gifs / images添加到我的页面,并希望在再次单击该可折叠标题或单击其他标题时删除它们。

我可以在点击时添加GIF,但无法弄清楚如何删除它们。我正在使用javascript和jquery。

以下是我的代码:

contentTitles = ["Test1", "Test2", "Test3"];
contentLinks = ["test1.gif", "test2.gif", "test3.gif"];

$(document).ready(function(){
  $('.collapsible').collapsible();
  $('main').append('<ul data-collapsible="accordion"></ul>');
  $('ul').addClass('collapsible popout');

for (var j = 0; j < contentTitles.length; j++) {
  $('ul').append('<li></li>');
  // start the creation of the collapsible
  $('.collapsible').collapsible({
      accordion: false, // A setting that changes the collapsible behavior to expandable instead of the default accordion style
    });
  };

// create the collapsible
$('li').append('<div><i></i></div>');
$('li').append('<div><span></span></div>');
$('i').addClass('material-icons');
$('i').parent().addClass("collapsible-header hoverable");
$('span').parent().addClass("collapsible-body");

// adds the titles to each collapsible header
$('.collapsible-header').each(function(index) {
  $(this).html(contentTitles[index]);
})

// adds the gif urls to each collapsible body
$('.collapsible-header').on('click', function() {
  $('.collapsible-body').each(function(index) {
    $(this).html('<iframe class="gif" src=' + contentLinks[index] + '>');
  })
})

$('.collapsible-header').on('click', function() {
  $('.collapsible-body').html();
})

})
});

谢谢。

1 个答案:

答案 0 :(得分:0)

.html()调用只返回元素的html内容 - 它不会改变它。如果要清空元素,请执行以下操作:

$('.collapsible-header').on('click', function() {
  $('.collapsible-body').html(""); //set HTML to be an empty string
})