如何在JavaScript中定义函数?

时间:2015-06-13 07:01:12

标签: javascript

如何定义功能?我想在FB.api中定义name1> name:name1,但我在控制台中出错了

Uncaught ReferenceError: name1 is not defined

这是我的JavaScript代码:

function share(platform) {
    var percent = $('.progress .percent').html().replace('%', '');
    var names = $('.progress .names').html().toUpperCase().split(' & ');
    var name1 = names[0];
    var name2 = names[1];

    var queryString =   encodeURIComponent('name1='+name1+'&name2='+name2+'&percent='+percent+'&text='+text+'&lang='+lang);
    // var json = JSON.stringify(queryString);
    var share_params = base64_encode(queryString);

    var share_url = 'http://example?';

    var url = 'https://www.facebook.com/sharer/sharer.php?u='+encodeURIComponent(share_url)+share_params;

    if(platform == 'whatsapp') {
        var share_title = name1+' + '+name2+' = '+percent+'%! '+window.famobi.__('shareText');
        var url = 'whatsapp://send?text='+encodeURIComponent(share_title);
    }

    window.open(url,'name','height=400,width=600');
    return false;
}

function sharefb(countr,share,platform) {
    $("div.bs-example").empty();
    $("p#share").html('<div class="col-lg-12 text-center"><div class="progress progress-striped active"><div id="statusbar"><div class="progress-bar progress-bar-info" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100" style="width:100%;"><span class="sr-only">20% Complete</span></div></div></div></div>');
    statusbar();
    var formdata = $("input#cache").val();
    var formdatav = $("input#cache").val();
    if (countr != "") {
        var formdata = formdatav.substr(0, formdatav.indexOf((countr + 1) + "."));
        if (formdata == "") {
            var formdata = $("input#cache").val();
        }
     }
    FB.api('/me/feed', 'post', {
        message: formdata,
        name: name1,
        description: "test des",
        caption: "Test app",
        link: "https://apps.facebook.com/*****/",
        picture: "http://examplepic.png"
    }, function(response) {
        console.log(response);
        if (!response || response.error) {
            alert('Error occured');
        }
        $("p#share").empty();
    });
}

1 个答案:

答案 0 :(得分:0)

很少有办法做到这一点。最简单:在function share(platform) {

之前坚持下去
var name1;

然后将var name1 = names[0];更改为

name1 = names[0];

这定义了一个全局var name1(第一位),然后确保你不重新创建一个局部变量(第二位)。

所以它变成了:

var name1;

function share(platform) {
    var percent = $('.progress .percent').html().replace('%', '');
    var names = $('.progress .names').html().toUpperCase().split(' &AMP; ');
    name1 = names[0];