How can I change the text of a <span> element?
I have a toggle button that I'm adding to an iFrame:
<script>
$('#list div').each(function(){
$(this).append('<span class="togglebutton">Maximize</span>');
});
开发者_JAVA技巧$("span.togglebutton").click(function() {
$(this).closest("li").children("div").toggleClass("maximized");
});
</script>
How can I change the toggle between the text Maximize/Minimize when the toggleClass is maximized?
$("span.togglebutton").click(function() {
var $this = $(this); // cache jquerized 'this'
$this.closest("li").children("div").toggleClass("maximized");
var currentText = $this.text();
// if the text is currently "Maximize"
if (currentText === "Maximize") {
// change it to new value
$this.text("New Text");
}
else {
// change it back to "Maximize"
$this.text("Maximize");
}
});
Well, if you are looking for some function like toogleClass()
to do that job for you, you are out of luck. AFAIK, you have to do it manually.
Do something like this
function toggleText() {
var curText = $("span.togglebutton").text();
var newText;
if(curText=="Maximize") { newText = "Minimize"; }
else { newText = "Maximize"; }
$("span.togglebutton").text(newText);
}
Now you can call it happily where you want to toggle it. Like
$("span.togglebutton").click(function() {
$(this).closest("li").children("div").toggleClass("maximized");
toggleText();
});
$(this).text('New Text');
OR
$(this).val('New Text');
Determine state.
if ($this.text() == 'Maximized') {
$(this).text('Minimized');
} else {
$(this).text('Maximized');
}
$("span.togglebutton").toggle(function() {
$(this).closest("li").children("div").addClass("maximized")
$(this).text("Maximized Text");
},function(){
$(this).closest("li").children("div").removeClass("maximized")
$(this).text("Minimized Text");
});
精彩评论