console.log($('.square').css('background-color')); // red
console.log($('.square')[1].css('background-color')); // error
console.log($('.square')[2].css('background-color')); // error
如何通过jquery检索绿色和蓝色方 block 的属性?
最佳答案
您应该使用eq
:
console.log($('.square').css('background-color'));
console.log($('.square').eq(1).css('background-color'));
console.log($('.square').eq(2).css('background-color'));
问题是 css
是 jQuery 对象的一个方法。但是,如果您使用方括号表示法来访问各个元素,您将获得“真正的”元素,而无需任何 jQuery 包装。
或者,您可以:
再次将其包装在 jQuery 对象中(昂贵,不推荐):
$($('.square')[1])
使用 vanilla-js 获取样式:
$('.square')[1].style.backgroundColor; // Only to get inline styles getComputedStyle($('.square')[1]).backgroundColor;
关于jquery - 通过索引检索具有类的某些元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24921496/