我刚开始使用Jquery,我有以下理解:
我的困惑是:
一个。一些函数如何返回正确的值,即使它们在包含许多元素的列表上运行,例如数据('某事')?
B中。如果我们特别想要对单个项目进行操作,我们应该怎么做?
答案 0 :(得分:3)
Jquery的每个选择器总是返回一个包装的项目列表......
不仅在与选择器一起使用时,而且是的,jQuery对象($()
的返回值)是元素的集,其中的方法可以作用于集合。
(很少,jQuery对象包含非元素的内容,例如,如果从回调中返回非元素,或者使用包含文本的map
,则contents
的返回值除了元素之外还注释节点。但在绝大多数情况下,你处理的是元素。)
一个。即使有些函数在具有许多元素的列表上运行,例如
data('something')
,某些函数返回正确的值是怎么回事?
非常好的问题! API是非对称。在大多数情况下,当您使用函数作为 getter 时,它会从集合中的第一个元素中获取;但是当你将它用作 setter 时,它会设置集合中的所有元素。考虑:
var a = $("a");
console.log(a.attr("href")); // Shows the href attr of the
// **first** element
a.attr("href", "http://stackoverflow.com"); // Sets the href attr of **all**
// elements in the set
此规则的一个重要例外是text
,它返回连接在一起的集合中所有元素的文本,而不仅仅是第一个元素的文本。为什么?呃...问John Resig。 :-)只是。
B中。如果我们特别想要对单个项目进行操作,我们应该怎么做?
如果你只是从集合中获取一个值,那么如果元素是第一个,你就没有什么特别的了;只需使用吸气剂(见上文)。
否则,您至少有两个选择:
使用$(yourSet[n])
围绕n
元素构建新集
jQuery对象是类似数组的;当您使用[]
表示法对其进行索引时,可以访问该索引处的原始元素。所以$(yourSet[n])
获取原始元素(yourSet[n]
),然后将其包装在jQuery对象中。
解决你的想法:
- 将整个列表视为常规数组
不确定;使用each
,它使用this
调用回调函数来引用集合中的每个条目。 (它也可以作为参数使用。)请注意,它将是原始条目(例如,原始DOM元素),而不是jQuery对象。
- javascript的过滤功能?
jQuery内置filter
(当你传递一个函数时)与JavaScript的Array.prototype.filter
非常相似。 (或者你可以传递一个字符串,当它用作CSS选择器时,它将根据它们是否与该字符串匹配来过滤该集。)
- 别的东西(想不通)
jQuery的访问器函数的另一个强大功能是它们中的大多数接受回调,它允许你循环遍历为每个元素设置不同值的元素(如果你想保持值不变,你可以不返回任何内容)对于他们中的一些)。例如,这会将文本中元素的索引附加到其文本中 - 但仅适用于具有奇数索引的条目:
$("some-selector").text(function(index) {
if (index % 2 === 1) {
return $(this).text() + " - " + index;
}
});
上述各种事例:
var divs = $("div.x");
// Getters get from the first entry in the set
console.log(divs.attr("class")); // "x a", the class of the first
// ...except for `text`, which is different:
console.log(divs.text()); // Text of all the elements joined together
// Setters set on all elements; this turns them all green:
divs.css("color", "green");
// Let's bold just the 3rd element:
divs.eq(2).css("font-weight", "bold");
// Let's make the 4th italic using [] notation:
$(divs[3]).css("font-style", "italic");
// Let's use `filter` to get just the elements with odd-numbered
// indexes, and use `each` on the result output their text
divs.filter(function(index) { return index % 2 === 1; }).each(function() {
console.log($(this).text());
});
// Let's use `text` to add the index to the end of each element:
divs.text(function(index) {
return $(this).text() + " - " + index;
});
// (Note: Using `css` above just to show how accessors work; in general
// prefer using classes to direct styling)
<div class="x a">first</div>
<div class="x b">second</div>
<div class="x c">third</div>
<div class="x d">fouth</div>
<div class="x e">fifth</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
结束时:在我看来,了解所有使用jQuery的方法的最佳方法是从头到尾简单地阅读the API documentation。它只需要一个小时,最多两个。然后一个月后再做一次。然后,当你来做某事时,即使你可能不记得你是怎么做的,你也会记得可以做到这一点,并且知道在API中再次找到它。