jquery 动态 id 选择器,删除然后添加类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3410766/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery dynamic id selector, remove then add class
提问by jp577
I have a table, with rows which all have a cell of a div with a dynamically generated id in the format of btn-insertidhere.
我有一个表格,其中的行都有一个 div 单元格,其中包含一个动态生成的 id,格式为 btn-insertidhere。
When the table row is selected, I want to select this div id, then remove a class and change it to another one. This is down to me wanting to have a button image change from an add symbol to a delete symbol which when clicked.
选择表格行时,我想选择这个div id,然后删除一个类并将其更改为另一个类。这取决于我想要将按钮图像从添加符号更改为单击时删除符号。
javascript code:
javascript代码:
$('*[class^=day] tbody tr[id^=band]').live('click', function() {
var DivId = $(this).find('div.add').attr('id');
alert(DivId);
$('DivId').removeClass('add').addClass('del');
$('table#fri_myTimes tbody').append($(this)).fadeIn(1000);
return false;
});
This is an html snippet of the dynamically generated code:
这是动态生成的代码的 html 片段:
<tr id="band-Modest-Mouse">
<td>Modest Mouse</td>
<td>15:25:00</td>
<td>16:10:00</td>
<td>45</td>
<td><div id="btn-Modest-Mouse" class="add"> </div></td>
</tr>
As you can see i want to change the 'add' class to a delete 'class'. All the table rows on the table is generated like this, so as you can see i've gone for the wildcard approach, which seems to work because the alert shown, shows the correct div id. I just need to change the class!
如您所见,我想将“添加”类更改为删除“类”。表上的所有表行都是这样生成的,所以你可以看到我已经采用了通配符方法,这似乎有效,因为显示的警报显示了正确的 div id。我只需要换班!
Thanks!
谢谢!
回答by Jaime
You either have to get the jq object for the div by removing the '.attr(id)' part
您要么必须通过删除 '.attr(id)' 部分来获取 div 的 jq 对象
var DivId = $(this).find('div.add');
...
$(DivId).removeClass('add').addClass('del');
or add a # in the divId selector
或在 divId 选择器中添加 #
$("#" + DivId).removeClass('add').addClass('del');
回答by calvinf
Try removing the quotes around DivId. It's a variable name and shouldn't be in quotes. As such:
尝试删除 DivId 周围的引号。这是一个变量名,不应该用引号引起来。像这样:
$(DivId).removeClass('add').addClass('del');
回答by Daniel
Since your variable DivId is a jquery object, you don't need the $()
at all:
由于您的变量 DivId 是一个 jquery 对象,因此您根本不需要$()
:
DivId.removeClass('add').addClass('del');