使用 jquery 变量调用函数

Call functions using a jquery variable

如何使用变量直接select 类等?

var $tbody = $(".tbl-locations-body");

$(".tbl-locations-body a.collapse").hide();
$(".tbl-locations-body tr.child-row").hide();
$(".tbl-locations-body .container").first().hide();
$(".tbl-locations-body .tab-content").hide();

我想使用$tbody来执行这些方法。语法是什么?

您可以使用 $tbody jQuery 对象中的 find() 方法。请注意,您也可以应用多个选择器来使调用成为一行:

var $tbody = $(".tbl-locations-body");
$tbody.find('a.collapse, tr.child-row, .container:first, .tab-content').hide();

您可以使用 find() 方法 - 请参阅下面的代码:

var $tbody = $(".tbl-locations-body");

$tbody.find("a.collapse").hide();
$tbody.find("tr.child-row").hide();
$tbody.find(".container").first().hide();
$tbody.find(".tab-content").hide();
var $tbody = $(".tbl-locations-body");
$("a.collapse", $tbody).hide();
// etc...

说明:

如果您将 $tbody 作为第二个参数传递给 jquery 函数,您将仅在该元素 ($tbody) 的范围内进行搜索,而不是在整个文档中进行搜索。

我一直在阅读这个,虽然

var $tbody = $(".tbl-locations-body");
$("a.collapse", $tbody).hide();

看起来更干净,但实际上它已更改为 $tbody.find()。所以更好的答案是使用 find 方法开始 - 正如 Rory 指出的那样,你也可以 select 多个。