在JQuery .each()函数中苦苦挣扎

时间:2012-05-04 10:49:19

标签: php jquery jquery-ui facebook-graph-api

希望这将是一个简单的解决方案,但我似乎无法自己解决。

背景是我正在尝试创建一个网络应用程序,将您所有的Facebook好友放入jQuery UI自动完成,并在您完成选择朋友并点击链接/按钮等后发布到他们的墙上。

我让这对一位朋友工作得很好,但是要求已经改变(一如既往)让这对多个朋友有用。

到目前为止,除了实际发布到用户朋友的墙上之外,我还有一些与多个朋友合作的事情。

代码

我会尽量将此与我认为的问题相关的代码保持如下:

我有一个隐藏的输入,我设法使用id填充:

<input id="fbid" type="hidden" value="12345, 567890, ">

然后我有一个jQuery函数,当点击链接发布到朋友的墙上时,它会运行。

<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
    FB.init({
        appId      : '12345678', // App ID
        channelUrl : '/channel.html', // Channel File
        status     : true, // check login status
        cookie     : true, // enable cookies to allow the server to access the session
        oauth      : true, // enable OAuth 2.0
        xfbml      : true  // parse XFBML
    });

    // Additional initialization code here

    FB.login(function(response)
    {
        if (response.authResponse)
        {                                               
            $("#send-voucher").click(function() {

                // Post message to friend's wall

                var opts = {
                    message : 'This is the message',
                    name : 'This is the name',
                    link : 'http://www.opticalexpress.co.uk',
                    description : 'This is the description',
                    picture : '/voucher_valid.png'
                };

                var referees = $("#fbid").val();

                // remove last comma and space from the end of the string
                referees = $.trim(referees);
                referees = referees.substring(0, referees.length - 1);

                var referee = referees.split(', '); // comma space
                referee.each(function() {

                    FB.api('/'+ referee +'/feed', 'post', opts, function(response)
                    {
                        if (!response || response.error)
                        {
                            alert('Posting error occured');
                        }
                        else
                        {
                            alert('Success - Post ID: ' + response.id);
                            $("#send-voucher").hide();
                            $("#voucher-sent").fadeIn('slow');
                        }
                    });
                });
            });
        }
        else
        {
            alert('Not logged in');
        }
    }, { scope : 'publish_stream' });
};

firebug报告的错误是referee.each is not a function

如果您需要任何进一步的信息,请告诉我。

3 个答案:

答案 0 :(得分:2)

它需要jQuery包装器,改变它:

referee.each(function() {

要:

$(referee).each(function() {

答案 1 :(得分:1)

您只能在jQuery对象上使用each()。您的referees变量是一个字符串数组,因此您需要从基础$ jQuery对象中调用它并将其作为参数传递,如下所示:

$.each(referee, function() {
    // ...
} 

或者,您可以将变量包装在jQuery对象中,如下所示:

$(referee).each(function() {
    // ...
}

答案 2 :(得分:1)

你必须这样称呼它:

$.each(referee, function() { ... });

jQuery.each()需要一个集合作为第一个参数,然后是一个回调函数。