Text change on click for toggling elements
I'm trying to change a '+' into '-' when toggling elements. I've tried a few things but once the symbol changes it won't toggle back and forth like it should. I've searched the other posts but they don't work for my bit of code.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"type="text/javascript"></script>
<script type="text/javascript">
$开发者_运维技巧(document).ready(function(){
//Hide (Collapse) the toggle containers on load
$("trace_dump").hide();
//Slide up and down on hover
$("h3").click(function(){
$(this).next("trace_dump").slideToggle("slow");
$(this).text($('span').text() == '+' ? '-' : '+');
});
});
</script>
...and here's the html:
<h3><span>+</span>print_r()</h3>
<trace_dump>
print_r($e);
</trace_dump>
<h3><span>+</span>var_dump()</h3>
<trace_dump>
var_dump($e);
</trace_dump>
Can I get some ideas?
In this line:
$(this).text($('span').text() == '+' ? '-' : '+');
this
is refering to the h3 and not the span
like I think you intended.
Try this:
$(this).find('span').text($(this).find('span').text()=='+'?'-':'+');
In your inline conditional check, you query for all <span>
elements and compare the .text()
contents. This obviously won't work. Use $(this).find('span')
or even better, do it like this:
$(this).find('span').text(function(i, text) {
return text === '+' ? '-' : '+';
});
Demo: http://jsfiddle.net/qR2NU/8/
I think, after the first call to your function, the span element is replaced by + or - And so from the next call onwards, jquery does not find the span element at all
I haven't tested it, but reading the code makes me believe this.
Maybe remove the span entirely and replace by + or -
Hope it helps
you need to enclose it in a div that supports show/hide operations. there is no html tag
This works. See demo heretrace_dump
UPDATE:
jQuery(document).ready(function() {
$("trace_dump").hide();
//Slide up and down on hover
$("h3").click(function(){
$(this).next("trace_dump").slideToggle("slow");
$(this).find("span").html(($(this).find("span").text().trim() == '+' ? '-' : '+'));
});
});
This will work as well. If you give the context as the second parameter, then the search is limited to within the enclosing element. In this case its "h3"
var element = $('span',$(this));
element.text(element.text() == '+' ? '-':'+');
精彩评论