jQuery 自定义插件元素计数器
jQuery custom plugin element counter
我正在创建 jQuery 插件来计算 DOM.
中有多少元素
这是我目前所做的。
jQuery 插件
$.fn.count = function(i) {
return this.each(function() {
++i;
return i;
});
}
HTML
<!DOCTYPE html>
<html lang="en">
<body>
<p>Sample text.</p>
<p>Sample text.</p>
<p>Sample text.</p>
</body>
</html>
运行 插件
console.log($("p").count());
错误
预期输出
3
插件中缺少什么?提前致谢:)
在您的插件中,您将返回 this
i:e 除了 <p>
删除它。
$.fn.count = function () {
var j = 0;
this.each(function () {
++j;
});
return j;
}
为什么不使用 length
属性 来查找 dom 中的元素数。
我正在创建 jQuery 插件来计算 DOM.
中有多少元素这是我目前所做的。
jQuery 插件
$.fn.count = function(i) {
return this.each(function() {
++i;
return i;
});
}
HTML
<!DOCTYPE html>
<html lang="en">
<body>
<p>Sample text.</p>
<p>Sample text.</p>
<p>Sample text.</p>
</body>
</html>
运行 插件
console.log($("p").count());
错误
预期输出
3
插件中缺少什么?提前致谢:)
在您的插件中,您将返回 this
i:e 除了 <p>
删除它。
$.fn.count = function () {
var j = 0;
this.each(function () {
++j;
});
return j;
}
为什么不使用 length
属性 来查找 dom 中的元素数。