2

如果以下选择器的长度为 0

$(".my_class")

我试着做$(".my_class").attr('value', 'test');

它不会导致任何错误,但我应该先检查长度吗?什么被认为是最佳实践?

我有一堆可能存在也可能不存在的属性,我想知道是否可以设置一个空的 jquery 值。

4

2 回答 2

2

不,你不应该先测试长度,这和做一样没用

if (n>0) {
 for (i=0; i<n; i++) {

事实上,这正是同一件事。

于 2013-02-06T17:30:15.153 回答
1

You don't need to test for length or anything first because jQuery returns an empty jQuery wrapped object, which is why you are even still able to run the method .attr() and it doesn't blow up on you!

This is definitely one of the many reasons jQuery is so powerful and easy to use for develoeprs.

于 2013-02-06T18:31:37.703 回答