【发布时间】:2014-12-05 14:50:45
【问题描述】:
我对 jQuery 和 JavaScript 有点了解,但在优化方面,我有点弱,但愿意学习新东西。
当用户单击适当的图像区域时,我目前正在从 Vimeo 将视频加载到我们的网站上。这工作正常,但我觉得这不是一种完全高效的方式。
有人发现我在下面编写的代码有什么问题可以做得更好吗?
JS
var videoData = [
{
'player_id':'video1',
'videoURL':'<?php the_field('two_vimeo_video_url'); ?>',
'width':'1000',
},
{
'player_id':'video2',
'videoURL':'<?php the_field('six_vimeo_video_url'); ?>',
'width':'1000',
}];
function loadVideo(target, videoid) {
$.getJSON('http://www.vimeo.com/api/oembed.json?url=' + encodeURIComponent(videoData[videoid]['videoURL']) + '&api=1&player_id='+ videoData[videoid]['player_id'] +'&width='+videoData[videoid]['width']+'&byline=0&color=ffffff&title=0'+'&callback=?', function(data){
$(target).find('.video-container').html(data.html); // puts an iframe embed from vimeo's json
$(target).closest('iframe').load(function(){
$f(player).addEvent('ready', function(id){
var vimeoVideo = $f(videoid);
});
});
});
}
$(function(){
// Create array to store values
var vimeoArray = [];
var videoContainer = $('.video-container');
// loop through st
$(videoContainer).each(function(index, value) {
// get the image with the data attr on each loop
var dataAttr = $(this).attr('data-video');
// if dataAttr is not false
if ( dataAttr !== undefined) {
// push data attribute value into array
vimeoArray.push(dataAttr);
// Store last element of array on iteration
var videoid = vimeoArray[vimeoArray.length-1];
// attach click handler to the parent of the scoped element
$(this).parent().click(function(){
// load the video
loadVideo(this, videoid);
$(this).unbind('click');
$(this).find('.b-studio__image').hide();
});
}
});
});
我已经创建了一个 jsfiddle 以及所有代码和一些虚拟数据,任何建议都会非常有帮助:)
【问题讨论】:
-
StackExchange 有一个对代码改进请求很好的网站。它叫代码审查:codereview.stackexchange.com 这种类型的问题会在那边得到更多的播放。
标签: javascript jquery api optimization vimeo