简体   繁体   中英

How to combine multiple scripts into one?

I've got five of the same scripts that just use five different variables. #video0 to #video4 . I'm just not quite sure on how to combine them all so I don't have redundant code. I've been trying to make them all variables

var video= [
$('#video0'),
$('#video1'),
$('#video2'),
$('#video3'),
$('#video4')
];

http://jsfiddle.net/cwfybnzr/

Use each() with the array

var videos = [
$('#video0'),
$('#video1'),
$('#video2'),
$('#video3'),
$('#video4')
];

$(function() {
    $.each(videos, function(){
        var iframe = $(this)[0];
        ...
    });

});

You can add a class element like videoCSS to all the elements and then loop through them like

$('.videoCSS').each(function(){
    var player = $(this);
    // your code here    
});

This way you can future proof you js code as you can add as many new player/iframes to the HTML with videoCSS class and your js code will still be the same.

Also, I found that in your code you are doing like

var iframe = $('#video0')[0];
var player = $(iframe);

Which means that first you are getting a jquery object using $('#video0') , then you are trying to get a DOM element out of it like $('#video0')[0] and then again you are converting it to a jquery object using $(iframe) .

I think there is no need of this much extra processing, you can simply use

var player = $('#video0');

or using my updated code like

var player = $(this);

UPDATED FIDDLE

Isn't it better to create class for those elements? Then it will be possible to iterate through them using simple jQuery syntax: $('.video') . Plus it would not require changing any JavaScript code when new videos will be added.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM