我想,jQuery,了解一个元素是否存在于另一个元素中.
有点像:
if($('#container').find('.search_element'))
如果.search_element进入#container,则必须返回YES,否则为否.
我该怎么做?尝试使用$.contains(‘#container’,’.search_element’),但似乎这个函数不起作用…
解决方法
¡¡¡更新!
看到我的答案[HERE]一个更强大的插件!
您可以轻松缩短@Chris的答案:
if($("#container .search_element").length) { ...
你也可以用一个有用的插件来做同样的事情:
jsFiddle
(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);
USE
// 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();
当然,这个插件可以进一步扩展到更多的花哨(一次处理多个调用,基于一个pram创建不存在的元素),但现在它是一个非常简单,非常需要的函数…这个元素存在吗?返回True或False