2017-09-16 98 views
0

我正在使用物化來創建可摺疊在我的頁面上的手風琴。我想在點擊可摺疊標題時將gif /圖像添加到我的頁面,並且當可摺疊標題再次單擊或單擊另一個標題時要將它們刪除。如何添加和刪除點擊GIF?

我可以在點擊時添加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(); 
}) 

}) 
}); 

謝謝。

回答

0

.html()調用只是返回元素的html內容 - 它不會更改它。如果你想清空元素,這樣做:在回覆

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

感謝當我設置HTML爲空字符串,我可以查看任何人之前,GIF被刪除。 – samiam0906

+0

我想你會附加兩個點擊處理程序 - 其中一個添加gif,另一個會立即刪除。我建議只使用一個處理程序,並檢查是否有gif要刪除,然後可以根據需要添加或刪除。 –