简体   繁体   English

如何使用带变量的 jQuery 选择器?

[英]How to use jQuery selectors with variables?

I have seen lots of similar questions, but none of answers worked in my case.我见过很多类似的问题,但没有一个答案适用于我的案例。

A variable is set depending on a document width:根据文档宽度设置变量:

if ($(document).width() < 1400) {
    var tblProdukty = document.getElementById('tblProdukty1280');
}
else {
    var tblProdukty = document.getElementById('tblProdukty1920');
}

Then I would like to do something like this: $("#tblProdukty1280 > tbody").empty();然后我想做这样的事情: $("#tblProdukty1280 > tbody").empty(); but with a variable set as above into something like this:但是将上面的变量设置为如下所示:

$("#" + tblProdukty + " > tbody").empty();

or或者

$(`${tblProdukty}` + " > tbody").empty();

I have tried different combinations of concatenation and injection and could not figure it out.我尝试了不同的连接和注入组合,但无法弄清楚。 I got the following error message: Uncaught Error: Syntax error, unrecognized expression: #[object HTMLTableElement] > tbody我收到以下错误消息:未捕获错误:语法错误,无法识别的表达式:#[object HTMLTableElement] > tbody

Can you please advice on this?你能就此提出建议吗?

You can do it in 2 different ways:您可以通过两种不同的方式进行操作:

first, you can use the tblProdukty variable as reference to the element:首先,您可以使用tblProdukty变量作为元素的引用:

if ($(document).width() < 1400) {
    var tblProdukty = $("#tblProdukty1280");
}
else {
    var tblProdukty = $("#tblProdukty1920"); 
}

Then use it this way:然后这样使用它:

tblProdukty.find("tbody").empty();

OR you can do something like that:或者你可以这样做:

if ($(document).width() < 1400) {
    var tblProdukty = "tblProdukty1280";
}
else {
    var tblProdukty = "tblProdukty1920";
}

Then use it this way:然后这样使用它:

$(`#${tblProdukty}` + " > tbody").empty();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM