如何将变量设置为空但可用的 Jquery 对象?

Kal*_*exx 3 javascript variables jquery

在 for 之外,我使用var list;. 我在 for 循环中使用这个变量,如下所示:

// add the html to the list
if (list == undefined)
    list = item;
else
    list.append(item.contents());
Run Code Online (Sandbox Code Playgroud)

item是从$('list_template').clone();调用构建的克隆 jquery 对象(list_template 是一个包含<li>元素的 div )。我正在做的是创建一个列表,然后我将在需要的地方 appendTo() 。

现在这段代码工作正常,但对我来说似乎不合适。不幸的是,我似乎无法弄清楚如何正确地将list变量声明为空的 Jquery 对象。我都试过:

var list = $([]);
var list = $('');
Run Code Online (Sandbox Code Playgroud)

这两者都会导致 append 无法正常工作(或按预期工作),而 list.html() 为 null。有没有办法将我的变量初始化为一个空的 jquery 对象,所以我所要做的就是list.append(item.contents());没有 if/else 语句?


编辑:为了减少混淆,这里是目前运行良好的整个 javascript 函数:

        var list;

        // Loop through all of the objects
        var objects = data.objects;
        for (x = 0; x < objects.length; x++) {
            // Clone the object list item template
            var item = $("#object_item_list_template").clone();

            // Setup the click action and inner text for the link tag in the template
            item.find('a').bind('click', { val: objects[x].Id }, function (e) { ShowObjectDetails(e.data.val); })
                          .html(objects[x].Name);

            // add the html to the list
            if (list == undefined)
                list = item;
            else
                list.append(item.contents());
        }
        // set the list of the topics to the topic list
        $("#object_list").empty();
        $('<ul>').appendTo("#object_list").append(list.contents());
Run Code Online (Sandbox Code Playgroud)

对象列表模板如下:

<div id="object_item_list_template" style="display:none">
    <li class="object_item"><a href="#"></a></li>
</div>
Run Code Online (Sandbox Code Playgroud)

通过克隆列表项、设置单击操作并将其添加到显示器上的列表,这一切都可以正常工作。

我试图摆脱 if/else 语句。我不能只做 list.append() 因为如果 list 未定义(或不​​是 Jquery 对象),它会引发异常。

use*_*716 5

一个空的 jQuery 对象被声明为:

$();
Run Code Online (Sandbox Code Playgroud)

jQuery 对象创建文档:http : //api.jquery.com/jQuery/


编辑:

听起来您正试图if/else通过扩展list它是否包含任何内容来消除该语句。

那正确吗?

如果是这样,请尝试以下操作:

list = $( list.get().concat(item.get()) );
Run Code Online (Sandbox Code Playgroud)

或者

$.extend(list, item);
Run Code Online (Sandbox Code Playgroud)

(假设刚list开始是一个空的 jQuery 对象。)


编辑:

由于您在循环中创建元素,因此您始终可以push()将其放入 jQuery 对象中。

尝试这样的事情:

var list = $();  // Start off with empty jQuery object.

...

list.push(item.find('li').get(0));  // A jQuery object is an Array. You can `push()` new items (DOM elements) in.

...

('<ul>').appendTo("#object_list").append(list);
Run Code Online (Sandbox Code Playgroud)

(我从原始编辑中只将 DOM 元素推送到 jQuery 对象中。)

应该将循环中的当前项目添加到您的列表中。

find()如果您只是克隆了 的子代,则可以消除代码中的调用#object_item_list_template

$('li', '#object_item_list_template').clone();  // Clone the `li` without the `div`.
Run Code Online (Sandbox Code Playgroud)

现在你有了li它自身的克隆。无需查找。