I have the following jQuery code:
我有以下jQuery代码:
var agencyToolbar = $('#agency-header-toolbar');
if ($(":not(:empty)", agencyToolbar)) {
agencyToolbar.show();
}
The code above works, but I wasn't sure if it's a proper way to use a jQuery selector.
上面的代码有效,但我不确定它是否是使用jQuery选择器的正确方法。
2 个解决方案
#1
1
Your code will always fire the show
as $(":not(:empty)", agencyToolbar)
creates a jQuery object which is never null
so is always "truthy".
您的代码将始终以$(“:not(:empty)”,agencyToolbar)创建一个永远不为null的jQuery对象来激活该节目,因此始终是“真实的”。
You wanted to use is
(which returns a boolean result) like
你想使用is(返回一个布尔结果)之类的
if (agencyToolbar.is(':not(:empty))')){
or use a single selector like
或使用单个选择器
$("#agency-header-toolbar:not(:empty)").show();
If you need it to be a tad faster, do the id selector first as its own operation, then filter it with not()
如果你需要它更快一点,首先将id选择器作为自己的操作,然后用not()过滤它
$("#agency-header-toolbar").not(":empty").show();
#2
1
Assuming that you want to select #agency-header-toolbar
which are not empty. It is more simpler to use
假设您要选择非空的#agent-header-toolbar。它使用起来更简单
var agencyToolbar = $("#agency-header-toolbar:not(:empty)");
agencyToolbar.show();
#1
1
Your code will always fire the show
as $(":not(:empty)", agencyToolbar)
creates a jQuery object which is never null
so is always "truthy".
您的代码将始终以$(“:not(:empty)”,agencyToolbar)创建一个永远不为null的jQuery对象来激活该节目,因此始终是“真实的”。
You wanted to use is
(which returns a boolean result) like
你想使用is(返回一个布尔结果)之类的
if (agencyToolbar.is(':not(:empty))')){
or use a single selector like
或使用单个选择器
$("#agency-header-toolbar:not(:empty)").show();
If you need it to be a tad faster, do the id selector first as its own operation, then filter it with not()
如果你需要它更快一点,首先将id选择器作为自己的操作,然后用not()过滤它
$("#agency-header-toolbar").not(":empty").show();
#2
1
Assuming that you want to select #agency-header-toolbar
which are not empty. It is more simpler to use
假设您要选择非空的#agent-header-toolbar。它使用起来更简单
var agencyToolbar = $("#agency-header-toolbar:not(:empty)");
agencyToolbar.show();