簡體   English   中英

jQuery:在選定項目之后從數組中刪除1個項目?

[英]jQuery: remove 1 item from array after the selected item?

我基於一些按鈕單擊創建一個數組。

每次單擊按鈕,我都會獲取其data-video值並將其添加到數組中。

然后,我立即在我添加到數組的每個視頻之后添加一個額外的視頻( intro.mp4 )。

這很好。

現在,如果我單擊與單擊一次相同的按鈕,則該項目將從陣列中刪除。

這也很好。

但是我還需要刪除為該特定視頻添加的intro.mp4 但是,當我嘗試執行代碼時,它將從我的數組中刪除所有intro.mp4項。 我只需要刪除所選項目后的1。

這是我的代碼,可幫助您更好地理解:

 var videoSource = []; $(document).on('click', '.pSelection', function(e) { var vidToAdd = $(this).attr("data-video"); ///check if its added///// if ($(this).hasClass("added")) { $(this).removeClass("added"); e.stopPropagation(); videoSource = videoSource.filter(x => x != vidToAdd); videoSource = videoSource.filter(x => x != 'intro.mp4'); console.log(videoSource); } else { $(this).addClass('added'); videoSource.push(vidToAdd); videoSource.push('intro.mp4'); var videoCount = videoSource.length; console.log(videoSource); e.stopPropagation(); $('.buildExDrop').hide(); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button class="pSelection" data-video="vid1.mp4"> Video 1 </button> <button class="pSelection" data-video="vid2.mp4"> Video 2 </button> <button class="pSelection" data-video="vid3.mp4"> Video 3 </button> <button class="pSelection" data-video="vid4.mp4"> Video 4 </button> <button class="pSelection" data-video="vid5.mp4"> Video 5 </button> 

據我了解,我的問題是代碼的這一部分:

videoSource = videoSource.filter(x => x != 'intro.mp4');

這是在告訴代碼從陣列中刪除intro.mp4所有實例。

但是我不知道如何在選定項目后僅將其定位為1。

有人可以就這個問題提出建議嗎?

要測試上面的代碼,請單擊幾個按鈕,然后繼續查看console.log(); ...

將一些項目添加到數組后,單擊已添加的按鈕之一,然后查看會發生什么。

您可以使用Array#splice()從已知項的索引處開始刪除2個項

 var videoSource = []; $(document).on('click', '.pSelection', function(e) { var vidToAdd = $(this).attr("data-video"); ///check if its added///// if ($(this).hasClass("added")) { $(this).removeClass("added"); e.stopPropagation(); // make sure value is in array let sourceIndex = videoSource.indexOf(vidToAdd); if (sourceIndex > -1) { // then remove 2 elements videoSource.splice(sourceIndex, 2) } console.log(videoSource); } else { $(this).addClass('added'); videoSource.push(vidToAdd); videoSource.push('intro.mp4'); var videoCount = videoSource.length; console.log(videoSource); e.stopPropagation(); $('.buildExDrop').hide(); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button class="pSelection" data-video="vid1.mp4"> Video 1 </button> <button class="pSelection" data-video="vid2.mp4"> Video 2 </button> <button class="pSelection" data-video="vid3.mp4"> Video 3 </button> <button class="pSelection" data-video="vid4.mp4"> Video 4 </button> <button class="pSelection" data-video="vid5.mp4"> Video 5 </button> 

您可以簡單地循環videoSource數組並找到需要刪除的videoLink索引並將其存儲在某個變量中。

var foundIndex = videoSource.indexOf("NAME OR LINK OF THE VIDEO");

然后刪除該項目,並刪除該鏈接旁邊的intro.mp4。 您可以使用foundIndex + 1刪除它

暫無
暫無

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

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