更改元素内容

Changing An Elements Content

我想通过单击按钮更改元素的内容,然后将其 return 恢复为原始消息。如果可能的话,我如何使用切换 class 来更好地做到这一点。

<doctype html>
<html>
<head>
<meta charset=utf-8>
<title>Day Practice</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"> </script>

</head>
<body>
<h1> HotDogs</h1>
<input type=button id=button value=button>
<script>
$("#button").click(function(){ 
$("h1").html("Change to this");
});


</script>

这会用一个按钮更改 header,但我不知道如何在再次单击该按钮时恢复它。也许切换 Class,我不知道。

设置一个标志来切换和检查,并在您更改时存储旧文本。一个例子:

var flag = false;
var old_text = "";

$("#button").click(function () {
    if (flag) {
        $("h1").html(old_text);
    } else {
        old_text = $("h1").html();
        $("h1").html("Change to this");
    }
    flag = !flag;    
});

这应该解决:

$( "#button" ).toggle(function() {
  $("h1").html("Change here");
}, function() {
  $("h1").html("Revert back here");
});

你可以试试这个:

var alternate_text = "Change to this";
$("#button").click(function(){ 
    var temp = $("h1").html()
    $("h1").html(alternate_text);
    alternate_text = temp; // Switch the two instances of text.
});

由于您更喜欢使用 toggleClass() 执行此操作,现在开始:

$(document).ready(function(){

    var oldContent;

    $("#button").click(function(){
        if($(".newCont")[0]){
            $("h1").html(oldContent);
        } else {
            oldContent = $("h1").html();
            $("h1").html("New text here");
        }

        $("h1").toggleClass("newCont");
    });
});