gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 10:25:15 24 4
gpt4 key购买 nike

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

// add the html to the list
if (list == undefined)
list = item;
else
list.append(item.contents());

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

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

var list = $([]);
var list = $('');

当 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());

对象列表模板如下:

<div id="object_item_list_template" style="display:none">
<li class="object_item"><a href="#"></a></li>
</div>

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

我正在尝试摆脱 if/else 语句。我不能只执行 list.append(),因为如果列表未定义(或不​​是 Jquery 对象),它会抛出异常。

最佳答案

一个空的 jQuery 对象声明为:

$();

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


编辑:

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

是这样吗?

如果是这样,尝试这样的事情:

list = $( list.get().concat(item.get()) );

$.extend(list, item);

(假设 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);

(我将原来的编辑为仅将 DOM 元素推送到 jQuery 对象中。)

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

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

$('li', '#object_item_list_template').clone();  // Clone the `li` without the `div`.

现在您有了 li 本身的克隆。无需查找。

关于javascript - 如何将变量设置为空但可用的 Jquery 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2912572/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com