我有一个 jQuery 函数,它可以通过单击 fieldset 的 legend 来切换其内容的可见性,仅留下 fieldset 边框(如果有)和 legend 显示:
$('legend.togvis').click(function() {
$(this).siblings().toggle();
return false;
});
除非fieldset包含文本节点,否则它运行得很好。
<fieldset><legend class='togvis'>Click Me</legend>
<p>I toggle when the legend is clicked.</p>
But I'm a recalcitrant text node and refuse to toggle.
</fieldset>
为了同时切换文本节点,我尝试了这个:
$('legend.togvis').click(function() {
$(this).parent().contents().not('legend').toggle();
return false;
});
这个函数的作用与第一个函数相同。还有这个:
$('legend.togvis').click(function() {
$(this).parent().contents(":not(legend)").toggle();
return false;
});
导致错误的代码
Message: 'style.display' is null or not an object
Line: 5557
Char: 3
Code: 0
URI: http://code.jquery.com/jquery-1.4.4.js
如何在单击图例时获取整个字段集(除传说之外)的全部内容?
ETA解决方案,非常感谢Eibx
$('legend.togvis').click(function() {
$(this).parent().contents().filter(
function() { return this.nodeType == 3; }).wrap('<span></span>');//wrap any stray text nodes
$(this).siblings().toggle();
});
.toggle()
通过影响节点的CSS来工作,它无法影响文本节点。也许我需要将fieldset的内容存储在.data()
中,然后删除子元素? - dnagirl