使用css类查找和删除特定元素
问题描述:
我远离JavaScript专家,但我试图将一些mootools代码迁移到jQuery,但我挣扎了!使用css类查找和删除特定元素
我有一个web表单,其中包含几个表的'.table-row'的css类。点击按钮后,我想查找所有具有“.table-row”的行,如果它们的display属性设置为none,我希望在提交之前将它们从页面中移除。
这是我的mootools代码:
function remove_hidden_elements() {
var myElements = $$('.table-row');
myElements.each(function (item, index) {
var vis = item.getStyle('display');
if (vis == 'none') {
item.dispose();
}
});
}
请可有人点我在正确的方向内的jQuery实现这一目标?
非常感谢提前。
答
jQuery和MooTools并不是真的那么遥远; jQuery是更面向集合的和更MooTools的元件取向,但除此之外,...
字面jQuery的等价物是:
function remove_hidden_elements() {
var myElements = $('.table-row');
myElements.each(function() {
if (this.style.display === 'none') {
$(this).remove();
}
});
}
基本上,交换$$()
为$()
(又名jQuery()
),并使用原始DOM元素,jQuery将通过它的版本each
来检查style.display
属性,然后使用remove
(它还会发现并销毁任何事件处理程序或其他相关数据,只要它们通过jQuery连接/关联)。
有些更地道jQuery的可能是:
function remove_hidden_elements() {
var myElements = $('.table-row');
myElements.each(function() {
var $this = $(this);
if ($this.is(":not(:visible)")) {
$this.remove();
}
});
}
甚至消除变量:
function remove_hidden_elements() {
$('.table-row').each(function() {
var $this = $(this);
if ($this.is(":not(:visible)")) {
$this.remove();
}
});
}
jQuery的:visible
选择的处理方式与文字style.display == 'none'
其他几起案件,并:not
反转了。 (或者而更直接,使用:hidden
作为3nigma points out —我一定是累了。)但是,如果你特别要处理的style.display == 'none'
只是这种情况下,(有什么不对的这一说法,它可以更有效),使用第一上面的例子(带或不带myElements
变量)。
答
用途:不和:可见选择过滤行。
试试这个:
function remove_hidden_elements() {
$('.table-row:not(:visible)').remove();
}
注:
按照jQuery的文档
Elements can be considered hidden for several reasons:
•They have a CSS display value of none.
•They are form elements with type="hidden".
•Their width and height are explicitly set to 0.
•An ancestor element is hidden, so the element is not shown on the page.
如果您严格寻找disaply:无过滤器,然后尝试:
function remove_hidden_elements() {
$('.table-row').filter(function(){
return (this.style.display === "none");
}).remove();
}
你能否提供你正在使用的HTML片段?目前还不清楚行或表是否有.table-row类 – spliter
到目前为止,它看起来并不像您已阅读[jQuery网站](http://jquery.com)上的基本文档。从“How Jquery Works”文章和“入门指南”教程开始。这将回答你很多问题。 –
@spliter - 这是有班级的行。对不起,我应该在我的帖子中更加明确。 – chut319