添加基于类或 id 的 jQuery 条件



我正在尝试为我的jQuery添加一个条件。 我的脚本是:

$("#mycontent a.half.first"+$id).removeClass("half").prependClass("paid");
$("#mycontent2 a.half.second"+$id).removeClass("half").prependClass("paid");

我在表格中有一个链接:

<table class='grav-results-table' id='mycontent' width='75%'>
<tr class="grav-results-tr">
<td class="grav-results-td">
<a href="#inbound" class="half first3547" onclick="comtype(3547,'inbound', 704)">$184.20</a>

我正在尝试定位上面显示的链接。 我尝试了以下不同的变体:

if ( $( "#mycontent" ).hasClass( "half first" ) ) {
$("#mycontent a.half.first"+$id).removeClass("half").prependClass("paid");
$("#mycontent2 a.half.second"+$id).removeClass("half").prependClass("paid");
}

我也尝试过:

if ( $( this ).hasClass( "half first" ) )

此代码位于我的 AJAX 脚本的成功区域中。

但我似乎找不到正确的方法来定位班级。 我做错了什么?

您需要更改 if 条件以在表的子级中查找类...喜欢这个:

if ($("#mycontent").find("a.half").length > 0) {
console.log('children found');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class='grav-results-table' id='mycontent' width='75%'>
<tr class="grav-results-tr">
<td class="grav-results-td">
<a href="#inbound" class="half first3547"></a>
</td>
</tr>
</table>

要添加到马丁,你可以试试这个。

if ( $( "table#mycontent" ).children().hasClass( "half first" ) ) {
alert("I have class in it.");
} 

最新更新