为什么必须从集合中重新选择JQuery元素? [英] Why do you have to re-select a JQuery element from a collection?

查看:56
本文介绍了为什么必须从集合中重新选择JQuery元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的页面上有许多复选框,每个复选框都有一个有用值的名称属性。

I have a number of check-boxes on my page, each has a name attribute for its useful value.

我想得到一个值列表仅检查项目。我可以得到像这样的元素的集合......

I want to get a list of values for the checked items only. I can get a collection of elements like so...

var checkedItems = $(".checkbox:checked");

现在我想创建一个列表(字符串),所以我创建一个循环......

Now I want to create the list (string) so I create a loop...

var list = "";
for (var i = 0; i < checkedItems.length; i++) {
    list += $(checkedItems[i]).attr("name") + "\n";
}

这适用于我的列表。但问题是,为什么我必须应用JQuery对象,即 $(...)才能使用attr属性?

This works and gives me my list. But the question is, why do I have to apply the JQuery object thingy i.e. $(...) to use the attr property?

如果我有以下内容而不会起作用...

if I had the following instead it would not work...

list += checkedItems[i].attr("name") + "\n";

但是数组肯定应该是JQuery元素的集合吗?为什么要重播?

But surely the array should be a collection of JQuery elements already? Why re-cast?

这是一个JSFiddle 如果有人想尝试它的工作示例

Here is a JSFiddle of the working example if anybody wants to try it

编辑:为什么这样做...

Why does this work...

var item = $("#item");
var name = item.attr("name");


推荐答案

你问题中的代码是错误的,因为

The code in your question is wrong, because

$(checkedItems[i].attr("name"))

应该是

$(checkedItems[i]).attr("name")






除此之外,你应该真的这样做


Besides that, you should really do it like this

var list = "";
checkedItems.each(function(){ list += this.name + '\n'; });

演示 http://jsfiddle.net/dGeNR/2/

之所以如此是不行的,是当你使用 [] 访问jQuery对象中的元素时,你会得到对DOM元素的直接引用,而不是另一个jQuery对象。

The reason it would not work, is that when you access the elements in the jQuery object with [] you get back a direct reference to the DOM element, and not another jQuery object.

这篇关于为什么必须从集合中重新选择JQuery元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆