2017-07-20 75 views
0

我想單擊按鈕時呈現適當的視頻。我可以在交換機或if中實現,但這意味着將來會做很多改變。試圖避免開關或如果與一個功能

任何人有一個想法如何優化它?

var Commercial = ["foNU8cPCaws", '7sZUZePLR-c', 'CrrSAc-vjG4', 'eaiGUVNZmD8']; 
var Documentary = ["UcQ4IcnZYUI", 'ORUoFcxJAb0', 'HRkm3javGfo', 'f5jyYqXmnhQ']; 
var isFirstPass = true; 

$('.category-button').on('click', function() { 
var $channelName = $(this).closest('div').prev('h2').text(); 
    showVideos($channelName); 
}); 

function showVideos(channelName) { 
    if (!isFirstPass) { 
    $('#addedContent').remove(); 
    } 

    $('#dropdownVideoPicker').append('<div id="addedContent"></div>'); 

    for (var i = 0; i < channelName.length; i++) { 
    $('#addedContent').append(generatePageCode(channelName[i])); 
    } 

    isFirstPass = false; 

    $('.videoThumbnail').on('click', function() { 
    grabYtId(); 
    }); 
} 

function grabYtId() { 
    console.log($(this).attr('src').slice(27, -6)); 
} 

我試圖做的是:當用戶點擊一個按鈕,該按鈕進入其父母的兄弟姐妹,H2,並調用一個函數,給它一個數組叫一樣的h2.text ()值

實施例與HTML

<div class="col-md-4 col-sm-4 col-xs-12 category-shape"> 
    <div class="inside-category col-md-4 col-sm-6 col-xs-12"> 
    <div class="col-md-12 text-center"> 
     <img style="margin-top:30px;" src="Assets/Images/Icons/commercial.png" alt="commercial" /> 
    </div> 
    <h2 class="col-md-12 text-center category-title">Commercial </h2> 
    <div class="col-md-12 text-center"> 
     <a target="_blank" href="https://www.youtube.com/watch?v=foNU8cPCaws&list=PLR1n4Pmhcag6H73FvubwoZUEkcf92Mr11"> 
     <button id="commercialButton" type="button" class="btn category-button"> 
      See The Videos 
     </button> 
     </a> 
    </div> 
    </div> 
</div> 

基本上我想避免此:

switch ($channelName) { 
    case "Commercial": 
    showVideos(Documentary); 
    break; 
    case "Documentary": 
    showVideos(Documentary); 
    break; 
} 

回答

0

鈣爲此使用一個對象,例如

const videoIds = { 
    documentary: ['UcQ4IcnZYUI', 'ORUoFcxJAb0', 'HRkm3javGfo', 'f5jyYqXmnhQ'], 
    commercial: ['foNU8cPCaws', '7sZUZePLR-c', 'CrrSAc-vjG4', 'eaiGUVNZmD8'] 
}; 

然後根據你所需要的選項,只是匹配鍵選擇它:videoIds.documentaryvideoIds.commercial

如果您嘗試訪問一個關鍵不在對象,它的值是剛剛返回爲undefined

+0

所以我會每次發送一個完整的對象? – alex3wielki