为什么js函数在另一个函数内部工作但不是唯一的

时间:2012-10-14 00:36:33

标签: javascript jquery

我在下面有这两个函数,无论出于何种原因,windowedBox函数仅在我从另一个函数调用它时才起作用。如果我直接调用windowedBox(),它什么都不做。如果我调用getShareButtons(),它会调用windowedBox()并正常工作。如果有人知道为什么会这样,请帮助我。 :(

注意::如果你想知道为什么它说$ j而不是$它因为我这样设置它。

function getShareButtons(){
    var postPath = window.location.pathname;
    var videoTitle = 'asdf';
    var videoURL = 'asdf';

    //Output social button attributes
    $j(".facebook-share").attr('href', 'asdf');
    windowedBox(); <---THIS CALL WORKS
}

function windowedBox() { 
    $j(".facebook-share, .twitter-share").click(function(){
        window.open(this.href, videoTitle, "width=626, height=436", "status=0", "toolbar=0");
        return false;
    });
}

2 个答案:

答案 0 :(得分:3)

我想这是因为你正在使用变量

videoTitle 

未在此函数中声明但在另一个函数中声明:)

答案 1 :(得分:2)

您收到错误是因为在第一个函数中设置了链接href属性,但如果您只调用第二个属性,则this.href保持未定义或为空

尝试这样

$j(".facebook-share").attr('href', 'asdf');
var videoTitle = 'Title';

windowedBox();

function windowedBox() { 
    $j(".facebook-share, .twitter-share").click(function(){
        window.open(this.href, videoTitle, "width=626, height=436", "status=0", "toolbar=0");
        return false;
    });
}