在Mootools中,我只需要运行if ($('target')){…}。if ($('#target')){…}在jQuery的工作方式相同?
当前回答
jQuery.fn.exists = function(selector, callback) {
var $this = $(this);
$this.each(function() {
callback.call(this, ($(this).find(selector).length > 0));
});
};
其他回答
jQuery.fn.exists = function(selector, callback) {
var $this = $(this);
$this.each(function() {
callback.call(this, ($(this).find(selector).length > 0));
});
};
如果你使用:
jQuery.fn.exists = function(){return ($(this).length > 0);}
if ($(selector).exists()) { }
你可能会暗示链条是可能的,但实际上不是。
这样会更好
jQuery.exists = function(selector) {return ($(selector).length > 0);}
if ($.exists(selector)) { }
还有另一种方式:
$('#elem').each(function(){
// do stuff
});
首先创建一个函数:
$.fn.is_exists = function(){ return document.getElementById(selector) }
then
if($(selector).is_exists()){ ... }
对我来说,.exists不起作用,所以我使用索引:
if ($("#elem").index() ! = -1) {}
推荐文章
- 在数组中获取所有选中的复选框
- 如何为Firebase构建云函数,以便从多个文件部署多个函数?
- 如何发送推送通知到web浏览器?
- AngularJS:工厂和服务?
- js:将一个组件包装成另一个组件
- 父ng-repeat从子ng-repeat的访问索引
- JSHint和jQuery: '$'没有定义
- 模仿JavaScript中的集合?
- 用JavaScript验证电话号码
- 如何在HTML5中改变视频的播放速度?
- 谷歌地图API v3:我可以setZoom后fitBounds?
- 用jQuery检查Internet连接是否存在?
- 如何使用滑动(或显示)函数在一个表行?
- ES6/2015中的null安全属性访问(和条件赋值)
- 与push()相反;