[英]Use variable as selector in function
On click, I want to get the name of the closest div and then look for all div's, that have this name attribute and add a class to them. 单击时,我想获取最近的div的名称,然后查找具有此name属性的所有div,并为它们添加一个类。
Here is my code: 这是我的代码:
HTML: HTML:
<div class="wrapper">
<div class="container" name="button1">
<div class="button">this is p #1</div>
</div>
</div>
<div name="button1">
somewhere else
</div>
JS: JS:
$('.wrapper').on("click", '.button', function() {
var attrname = $(this).closest('.container').attr('name');
$("div[name=attrname]").each(function() {
$(this).addClass("classtobeadded");
});
});
But it is not working. 但它没有用。 So, how can I use the variable in here: 那么,我如何在这里使用变量:
$("div[name=attrname]").each(function()
There's a few issues with your logic. 您的逻辑存在一些问题。 Firstly the .container
element does not have the name
attribute, the .button
does, so you don't need to use closest()
. 首先.container
元素没有name
属性, .button
,所以你不需要使用.button
closest()
。 Secondly, you need to concatenate the actual name value in to the selector. 其次,您需要将实际名称值连接到选择器。 Lastly div
elements do not have a name
attribute so the HTML is invalid. 最后, div
元素没有name
属性,因此HTML无效。 If you want to store custom meta-data on an element use a data
attribute instead. 如果要在元素上存储自定义元数据,请使用data
属性。
Also note that you don't need the each()
loop, you can just call addClass()
on the collection selected with the data-name
attribute. 另请注意,您不需要each()
循环,只需在使用data-name
属性选择的集合上调用addClass()
。 Try this: 尝试这个:
$('.wrapper').on("click", '.button', function() { var attrname = $(this).data('name'); $('div[data-name="' + attrname + '"]').addClass("classtobeadded"); });
.classtobeadded { background: red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="wrapper"> <div class="container"> <div class="button" data-name="button1">this is p #1</div> </div> </div> <div data-name="button1"> somewhere else </div>
You have to concatenate it properly, 你必须正确地连接它,
$(`div[name=${attrname}]`).each(function() {
And by the way, when looking at your code there is no attribute available in the closest div with a class .container
. 顺便说一句,在查看代码时,最近的div中没有可用的属性.container
。 Check that as well. 检查一下。
$("div[name=" + attrname + "]").each(function() {})
要么
$(`div[name=${attrname}]`).each(function() {})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.