我想,对于jQuery,了解一个元素是否存在于另一个元素中.
有些事情如下:
if($('#container').find('.search_element'))
Run Code Online (Sandbox Code Playgroud)
如果必须返回YES .search_element是进入#container,否则为NO.
我该怎么做?尝试使用$ .contains('#container','.search_element'),但似乎这个函数不起作用......
Chr*_*ris 19
一个简单的长度检查:
if($("#container").find(".search_element").length) {
// If the length is greater than 0, it exists
} else {
// else, false
}
Run Code Online (Sandbox Code Playgroud)
SpY*_*3HH 13
见我的回答[ 这里 ]为MUCH更强大的插件!
您可以通过以下方式轻松缩短@Chris答案:
if($("#container .search_element").length) { ...
Run Code Online (Sandbox Code Playgroud)
您也可以使用我为此制作的有用插件执行相同的操作:
(function($) {
if (!$.exist) {
$.extend({
exist: function(elm) {
if (typeof elm == null) return false;
if (typeof elm != "object") elm = $(elm);
return elm.length ? true : false;
}
});
$.fn.extend({
exist: function() {
return $.exist($(this));
}
});
}
})(jQuery);
Run Code Online (Sandbox Code Playgroud)
使用
// With your if statement
if($("#container .search_element").exist()) { ...
// With ID
$.exist("#eleID");
// OR
$("#eleID").exist();
// With class name
$.exist(".class-name");
// OR
$(".class-name").exist();
// With just tag // prolly not best idea aS there will be other tags on site
$.exist("div");
// OR
$("div").exist();
Run Code Online (Sandbox Code Playgroud)
当然这个插件可以进一步扩展到更加花哨(一次处理多个调用,根据婴儿车创建不存在的元素),但是就像现在一样,它做了一个非常简单,非常需要的功能......这个元素存在吗?回来True或False
| 归档时间: |
|
| 查看次数: |
24171 次 |
| 最近记录: |