我点击按钮时尝试渲染适当的视频。我可以在交换机或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 :(得分:0)
可以使用一个对象,例如
const videoIds = {
documentary: ['UcQ4IcnZYUI', 'ORUoFcxJAb0', 'HRkm3javGfo', 'f5jyYqXmnhQ'],
commercial: ['foNU8cPCaws', '7sZUZePLR-c', 'CrrSAc-vjG4', 'eaiGUVNZmD8']
};
然后根据您需要的选项,只需使用匹配的密钥选择它:videoIds.documentary
,videoIds.commercial
等。
如果您尝试访问不在对象中的键,则其值仅返回为undefined
。