如何避免在JavaScript中重复?

时间:2014-04-10 03:49:43

标签: javascript function

我如何避免这种重复的代码? 我是javascript的新手。 我需要用不同的参数调用相同的函数,如100次, 并且还有100个不同的getElementBys

(function() {

    var ok, publicSessionID, sms, a, b, c, d, e, f, g, h, i, j;

    var pubnub = PUBNUB.init({
        subscribe_key: '',
        publish_key: ''
    });


    function getParameterByName(name) {
        name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
        var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
            results = regex.exec(location.search);
        return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
    };

    var publicSessionID = getParameterByName('tv') || 'default';
    var sms = getParameterByName('sms') || 'default';
    var a = document.getElementById("channel1");
    var b = document.getElementById("channel2");
    var c = document.getElementById("channel3");


    d.onclick = function() {
        pubnub.publish({
            channel: publicSessionID,
            message: {
                "action": "tv.new.channel.4"
            }
            uuid: sms,
            callback: function(info) {
                console.log(JSON.stringify(info));
            }
        })
        return false;
    };

    e.onclick = function() {
        pubnub.publish({
            channel: publicSessionID,
            message: {
                "action": "tv.new.channel.5"
            }
            uuid: sms,
            callback: function(info) {
                console.log(JSON.stringify(info));
            }
        });
        return false;
    };

    f.onclick = function() {
        pubnub.publish({
            channel: publicSessionID,
            message: {
                "action": "tv.new.channel.6"
            }
            uuid: sms,
            callback: function(info) {
                console.log(JSON.stringify(info));
            }
        });
        return false;
    };
})()

var a,通过z会变得重复 和 a.onclick = function(){}越来越有争议,在js中有什么更有效的方法吗?

感谢

4 个答案:

答案 0 :(得分:0)

function pubnub (channel) {
    pubnub.publish({
        channel : publicSessionID,
        message : {"action": "tv.new.channel.5"} //use channel here
            uuid : sms ,
            callback : function(info) {
            console.log(JSON.stringify(info));
        }           
    });     
    return false;
}; 

只需将其设为带有通道参数的函数,并将其称为

e.onclick = function() { pubnub(5); }

只需注意,onclick只允许一个事件,因此请考虑使用addEventListener

答案 1 :(得分:0)

编写函数生成器

function generatorFunction(channel) {
    return function() {
        pubnub.publish({
            channel: publicSessionID,
            message: {
                "action": channel
            }
            uuid: sms,
            callback: function(info) {
                console.log(JSON.stringify(info));
            }
        });
        return false;
    }
};

并以通道作为参数调用它以获取具有指定通道的新函数

for (var i = 1; i <= 26; i += 1) {
    var currentChannel = document.getElementById("channel" + i);
    currentChannel.onclick = generatorFunction("tv.new.channel." + i);
}

答案 2 :(得分:0)

看起来你可以利用这里的命名约定来避免输入100次调用getElementById;

var elements = [];
for(var i = 0; i < 100; i++){
  var e = document.getElementById("channel" + i);
  elements.push(e); 
}

答案 3 :(得分:0)

您可以在元素上使用类,例如添加class='channels'。你可以这样做,

var channels = document.querySelectorAll(".channels");

for (var i = 0;  i < channels.length; i++) {
    var ch = channels[i]
    , ch_num = i

    ch.addEventListener('click', function () {
        pubnub.publish({
            channel: publicSessionID,
            message: {
                "action": "tv.new.channel." + i
            } //use channel here
            uuid: sms,
            callback: function (info) {
                console.log(JSON.stringify(info));
            }
        });
        return false;
    });
}