Jquery - 使用 .this 从一组按钮中选择特定按钮



我有一组具有相同类名的按钮,如果没有 URL,有时需要将一个按钮灰显。我正在尝试通过向该特定按钮添加 css 类.not-available来做到这一点。但这也会将类名添加到所有其他按钮。这是代码:

$('a').each(function(index) {
if( $(this).attr('href') == '' ) {
$('.button').addClass('not-available')
}

您的 if 语句引用$('.button')这将影响.button的所有实例,而不仅仅是那些带有空白href的实例。 将您的选择器更改为$(this),这将仅针对您的条件中匹配的选项。

$('a').each(function(index) {
if( $(this).attr('href') == '' )
{
$(this).addClass('not-available')
}

这将起作用,我测试了... 使用"find(("方法来实现此目的...

$('a').each(function(index) {
if($(this).attr('href') == '') {
$(this).find(".button").addClass('not-available');
}
}

最新更新