[英]How to include a variable in a jQuery selector?
In my JavaScript, I have a variable called counter
. 在我的JavaScript中,我有一个名为
counter
的变量。 And I want to append it to a select tag's ID that I dynamically created using my script like- 我想将其附加到我使用脚本动态创建的选择标签的ID上,例如-
// Creating a <div>
var random_div = $(document.createElement('div'))
.attr("class", "col-md-7");
counter = 5;
random_div.after().html('<select multiple class="js-example-basic-multiple" name="tal' + counter + '" id="tal' + counter + '" > </select>');
random_div.appendTo(main_div);
Now, I'm trying to resolve width of this newly created select
tag, but it doesn't work- 现在,我正在尝试解析此新创建的
select
标签的宽度,但是它不起作用-
$("#tal" + counter).select2({width: 'resolve'});
I even tried it with another variable, but that doesn't work either- 我什至尝试了另一个变量,但这也不起作用-
var testing = '#tal' + counter;
$(testing).select2({width: 'resolve'});
Now, if I hard-code this to say $("#tal5").select2({width: 'resolve'});
现在,如果我将其硬编码为
$("#tal5").select2({width: 'resolve'});
, it works. , 有用。
This is really elementary, but I can't seem to figure out a solution. 这真的很基础,但是我似乎找不到解决方案。
Do not look up the element, generate the element with jQuery and use the reference 不要查找元素,使用jQuery生成元素并使用引用
const select = $('<select ...></select'); // make the select
yourElem.append(select) // add it
select.select2({width: 'resolve'}); // fire the select2
There are some js errors because of miss escaping of single quotes and double quotes 由于遗漏了单引号和双引号而导致了一些js错误
var random_div = $(document.createElement('div')) .attr("class", "col-md-7"); counter = 5; random_div.after().html('<select multiple class="js-example-basic-multiple" name="tal'+counter+'" id="tal'+counter+'" > </select>'); console.log($(random_div).find('#tal'+counter)[0])
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
try this, now its working 试试这个,现在可以工作了
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.