jQuery append() - 看起来像它应该工作,但不是

时间:2012-02-17 22:46:23

标签: jquery

我在向动态创建的div添加get()时遇到问题。我标记了一条给我带来麻烦的代码。有人可以看一看,看看它有什么问题吗?

var weekday = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'],
        today = new Date().getDay(),
        list = $('ul.yui-nav');

    for(var x=0;x<=6;x++){
        $('#' + weekday[x]).hide();
        list.append(
            $('<li></li>', {
                html : '<a href = "#' + weekday[x].toLowerCase() + '">' + weekday[x] + '</a>'
            }).toggleClass(function(){
                if(today == x){
                    return 'selected';
                }
            }).bind('click', function(e){
                e.preventDefault();
                $(this).parent().children('li').removeClass('selected');
                $(this).addClass('selected');
                $('#' + weekday[x]).hide();
                $('#' + weekday[x]).show();
            })
        );



                    // the 5 lines below is where I'm having trouble
        $('div.yui-content').append(
            $('<div class="content" id="' + weekday[x] + '"></div>').append(
                $.get('index.php')
            )
        );

    }

2 个答案:

答案 0 :(得分:4)

$.get返回一个XHR对象,而不是HTML字符串或有效的HTML元素。

$.get也是异步的,所以你需要使用它的回调才能使用它来自服务器的响应:

    //make AJAX call to `index.php`, storing the server-response in the `serverResponse` variable
    $.get('index.php', function (serverResponse) {

        //select the element to append-to
        $('div.yui-content').append(

            //create a new div and append the server-response to it
            $('<div class="content" id="' + weekday[x] + '"></div>').append(serverResponse));
    });

由于您无论如何要编制HTML字符串,您只需将serverResponse直接放入.content div的创建中:

        $('div.yui-content').append(
            $('<div class="content" id="' + weekday[x] + '">' + serverResponse + '</div>'));

更新

由于您在循环内运行此操作,因此您可以使用闭包来保持x的值不受回调函数的影响:

(function(newX) {
    $.get('index.php', function (serverResponse) {
        $('div.yui-content').append(
            $('<div class="content" id="' + weekday[newX] + '"></div>').append(serverResponse));
    });
})(x);

这是必要的,因为当回调函数执行时,循环范围内x的值将发生变化。使用闭包我们基本上创建了一个新的范围(函数),其中x的值被“保存”(如newX)直到需要它(可能是将来的任何时间)。 / p>

另外,我建议缓冲你附加到DOM的HTML并立即添加它,而不是在循环的每次迭代中调用.append()

 list = [];

    for(var x=0;x<=6;x++){
        $('#' + weekday[x]).hide();
        list.push(...

然后在循环完成后运行:

for (...) {...}
$('ul.yui-nav').append(list.join(''));

答案 1 :(得分:0)

$.get进行ajax调用async本质上它会返回一个xhr对象。因此,要么在$.get的回调中执行代码,要么可以像这样使用load方法。

$('<div />', { 
      class: "content", 
      id: weekday[x] 
})
.appendTo('div.yui-content')
.load('index.php');

注意,我使用appendTo方法在div.content内追加动态创建的div.yui-content

如果您使用load,则不必创建闭包,因为在调用div之前已创建load

相关问题