问题描述
|
我有一个相当普通的jQuery,当单击+时切换div的可见性,单击-时将其隐藏(单击时+变为-)。问题在于+/-切换器会跟随某些文本,该文本有时带有+或-并同时切换。例如:了解有关blah-blah +的更多信息。单击时,加号变为减号。再次单击时,两个减号都变为加号。
我想如果我只是将+更改为
+
,将减号更改为—
;在jQuery中,它可以解决问题,但不起作用。 div可见性可切换为开/关,但加/减符号不变。
这是脚本:
function toggleSpecial(element)
{
jQuery(element).next(\".hidden\").slidetoggle(\"fast\");
jQuery(element).html(function(i,html) {
if (html.indexOf(\'+\') != -1 ){
html = html.replace(\'+\',\'-\');
} else {
html = html.replace(\'-\',\'+\');
}
return html;
});
}
这是用HTML代码替换+和-的脚本,该脚本不起作用。
function toggleSpecial(element)
{
jQuery(element).next(\".hidden\").slidetoggle(\"fast\");
jQuery(element).html(function(i,html) {
if (html.indexOf(\'+\') != -1 ){
html = html.replace(\'+\',\'—\');
} else {
html = html.replace(\'—\',\'+\');
}
return html;
});
}
关于我在做什么错的任何想法或建议吗?谢谢!
解决方法
您是基于可见性来切换完全任意的东西。为什么不只是看它是否可见?此外,您可以将字符包装成一个跨度,然后执行以下操作:
$(\'#iamelement\').click(function() {
var $this = $(this);
$this.next(\".hidden\").slideToggle(\"fast\",function() {
$this.find(\'span\').text($(this).is(\':visible\') ? \'-\' : \'+\');
});
});
这将是这样的:
<a href=\"#\" id=\"iamelement\">toggle thing <span>+</span></a>
<div class=\"hidden\">
thing
</div>
证明在小提琴中:http://jsfiddle.net/rFeeJ/1/
附加内容:
要使其通用,您需要使用类而不是ID。我只是想举例说明。
<a href=\"#\" class=\"toggler\">toggle thing <span>+</span></a>
<div class=\"hidden\">
thing
</div>
<a href=\"#\" class=\"toggler\">toggle thing 2 <span>+</span></a>
<div class=\"hidden\">
thing 2
</div>
<a href=\"#\" class=\"toggler\">toggle thing 3 <span>+</span></a>
<div class=\"hidden\">
thing 3
</div>
$(\'a.toggler\').click(function() {
var $this = $(this);
$this.next(\".hidden\").slideToggle(\"fast\",function() {
$this.find(\'span\').text($(this).is(\':visible\') ? \'-\' : \'+\');
});
});