我正在尝试从设置为 inline
的表中获取选中的选项。有一个搜索功能,它在与搜索不匹配的对象上设置 $(element).css('display','none')
。无论如何,这段代码只会返回 inline
,无论元素设置成什么。即使我在表本身中手动将它们全部设置为 display: none
,警报也会为表中的每个对象返回 inline
。有什么解决办法吗?
JS代码:
function pass_QR() {
var i = 0;
var array = [];
$("input:checkbox:checked").each(function () {
i++;
alert($(this).css('display'));
if ($(this).val() !== 0 && $(this).css('display') === 'inline') {
array.push($(this).val());
}
});
}
最佳答案
从根本上说,css("display")
确实有效,所以其他事情正在发生。
我怀疑以下两件事之一:
您正在制作的复选框
display: none
永远不会checked
,因此您在each
中看不到它们循环。您没有勾选复选框
display: none
,而是对它们的某些祖先元素执行此操作。在这种情况下,$(this).is(":visible")
正是您要找的。p>
这是#2 的示例:Live Copy | Live Source
<div id="ancestor">
<input type="checkbox" checked>
</div>
<script>
$("#ancestor").css("display", "none");
console.log("display property is now: " +
$("input:checkbox:checked").css("display"));
console.log("visible tells us what's going on: " +
$("input:checkbox:checked").is(":visible"));
</script>
...输出:
display property is now: inline-block visible tells us what's going on: false
Applying that to your code:
function pass_QR() {
var i = 0;
var array = [];
$("input:checkbox:checked").each(function () {
i++;
alert($(this).css('display'));
if ($(this).val() !== 0 && $(this).is(':visible')) {
// Change is here -----------------^^^^^^^^^^^^^^
array.push($(this).val());
}
});
}
旁注:每次您调用 $()
,jQuery 必须做一些工作。当您发现自己在同一个作用域中重复调用它时,最好一次完成该工作:
function pass_QR() {
var i = 0;
var array = [];
$("input:checkbox:checked").each(function () {
var $this = $(this); // <=== Once
i++;
alert($this.css('display'));
if ($this.val() !== 0 && $this.is(':visible')) {
// Other change is here -------^^^^^^^^^^^^^^
array.push($this.val());
}
});
}
关于javascript - jQuery.css ('display' ) 只返回内联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18181490/