开发者

javascript jquery: Overwriting variables - how? better performance?

Hey guys, i'm not much of a hardcore coder and so I don't get this basics here.

Imagine I have multiple 's on my page (that contain Youtube Videos via swfobject). All those object's have a unique ID like ytplayer_12, ytplayer_2, ytplayer_56, etc.

I need to run through all of this ytplayer_'s with jquery and add an EventListener to them.

It works just fine! I just wonder if I'm declaring the variables ($ytid, ytid) in the right place - outside of the onYouTubePlayerReady() function? Or should I declare the vars inside of the function? Or even inside of the each-loop?

var $ytid = '',
    ytid = '';

function onYouTubePlayerReady() {

    $('object[id^="ytplayer_"]').each(function()开发者_StackOverflow中文版 {

        $ytid = $(this).attr('id');
        ytid = document.getElementById($ytid);

        ytid.addEventListener("onStateChange", "foo");

    });
};

I'm just curious what is better in this case and if I'm doing that correct right now? Thank you for your info and help?


Declaring variables at global scope is bad idea. Move them into function scope.

function onYouTubePlayerReady() {
    var $ytid = '', ytid = '';
    $('object[id^="ytplayer_"]').each(function() {
        $ytid = $(this).attr('id');
        ytid = document.getElementById($ytid);

        ytid.addEventListener("onStateChange", "foo");
    });
};

And you can get rid of them:

function onYouTubePlayerReady() {
    $('object[id^="ytplayer_"]').each(function() {
        this.addEventListener("onStateChange", "foo");
    });
};


Since the variables' values are unique to each iteration, you definitely need to define them inside the loop. Although you can make life a little easier for yourself and leave out the document.getElementById() call, since this is already pointing to the object you're looking for:

var ytid = this;
var $ytid = $(this).attr('id'); // only if you need the id for something other than instantiating the ytid variable

I used var as per gor's suggestion not to make the variables global

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜