0

所以我试图遍历一些元素并根据 ajax 调用的结果更改一些文本。问题是我无法从 ajax 回调中获取数据,而且我不确定如何将事件链接起来。我得到了一个股票报价值,如果我可以将该对象返回到先前的范围、匹配循环,然后在那里进行所有操作,那就太好了。

$(function(){
          var tweets = $('.tweet');
          var symbol_pat = /(^|\s\$)([a-z]+\b)/gi;
          $.each(tweets, function(){
            var tweet_html = $(this).html();
            tweet_html = tweet_html.replace(symbol_pat,function(){
               var symbol = arguments[2];
               var YAHOO_API_URL = 'http://query.yahooapis.com/v1/public/yql'
               var format = 'json'
               var query = 'select * from yahoo.finance.quotes where symbol in ("'+symbol+'")';
               var env = "store://datatables.org/alltableswithkeys";

               $.ajax({
                    'url':YAHOO_API_URL,
                    'async':false,
                    'method':'GET',
                    'data': {
                        'format':format,
                        'q':query,
                        'env':env
                    },
                    success: function(data){
                        var quote = data.query.results.quote;
                        var change = quote.Change;
                        var change_pct = quote.ChangeinPercent;
                        var quote_price = quote.LastTradePriceOnly;
                        var html_str = "";

                        if( change.indexOf("+") != -1 ){
                            html_str = '<span class="symWrap up">'+arguments[0]+'</span>';
                        }else{
                            html_str = '<span class="symWrap down">'+arguments[0]+'</span>';
                        }

                        tweet_html = arguments[0].replace(html_str);
                        $(this).html(tweet_html);
                    }
               });

            });
          });

        });
4

2 回答 2

0

$.ajax()异步运行,因此您不能真正“等待”前一个范围内的成功。不过,您可以使用 jQuery promise 和 Deferred 来执行此操作。查看http://www.erichynds.com/jquery/using-deferreds-in-jquery/http://joseoncode.com/2011/09/26/a-walkthrough-jquery-deferred-and-promise/

编辑:显示不需要承诺或延迟的替代解决方案:

$(function(){
  var tweets = $('.tweet');
  var symbol_pat = /(^|\s\$)([a-z]+\b)/gi;
  $.each(tweets, function(){
       var that = this;

       var symbol = arguments[2];
       var YAHOO_API_URL = 'http://query.yahooapis.com/v1/public/yql'
       var format = 'json'
       var query = 'select * from yahoo.finance.quotes where symbol in ("'+symbol+'")';
       var env = "store://datatables.org/alltableswithkeys";

       $.ajax({
        'url':YAHOO_API_URL,
        'async':false,
        'method':'GET',
        'data': {
        'format':format,
        'q':query,
        'env':env
        },
        success: function(data){
        var quote = data.query.results.quote;
        var change = quote.Change;
        var change_pct = quote.ChangeinPercent;
        var quote_price = quote.LastTradePriceOnly;
        var html_str = "";

        if( change.indexOf("+") != -1 ){
            html_str = '<span class="symWrap up">'+arguments[0]+'</span>';
        }else{
            html_str = '<span class="symWrap down">'+arguments[0]+'</span>';
        }

            var tweet_html = $(that).html();
                var tweet_html = arguments[0].replace(html_str);
            tweet_html = tweet_html.replace(symbol_pat,html_str);
        $(that).html(tweet_html);
        }
       });

    });
  });

});
于 2012-05-18T01:54:14.480 回答
-1

只要您的replace代码是正确的,我相信您的代码的以下返工应该可以工作(或者至少让您非常接近,因为这未经测试并且取决于您的代码的其余部分):

$(function(){

    var YAHOO_API_URL = 'http://query.yahooapis.com/v1/public/yql'

    var tweets = $('.tweet');
    var symbol_pat = /(^|\s\$)([a-z]+\b)/gi;
    $.each(tweets, function(){
        var tweet_html = $(this).html();
        tweet_html = tweet_html.replace(symbol_pat, function(){
            var symbol = arguments[2];
            var format = 'json'
            var query = 'select * from yahoo.finance.quotes where symbol in ("'+symbol+'")';
            var env = "store://datatables.org/alltableswithkeys";
            var quoteHtml = getQuote(format, query, env, function(quote) {
                var change = quote.Change;
                var change_pct = quote.ChangeinPercent;
                var quote_price = quote.LastTradePriceOnly;
                var html_str = "";

                if( change.indexOf("+") != -1 ){
                    html_str = '<span class="symWrap up">'+arguments[0]+'</span>';
                }
                else{
                    html_str = '<span class="symWrap down">'+arguments[0]+'</span>';
                }
                return arguments[0].replace(html_str);
            });
            return quoteHtml;
        });
        $(this).html(tweet_html);
    });

    var getQuote = function(format, query, env, successCallback) {
       $.ajax({
            'url':YAHOO_API_URL,
            'async':false,
            'method':'GET',
            'data': {
                'format': format,
                'q': query,
                'env': env
            },
            success: function(data){
                var quote = data.query.results.quote;
                if(successCallback !== undefined && typeof successCallback == 'function') {
                    successCallback(quote);
                }
            }
       });
    };
});
于 2012-05-18T02:18:26.667 回答