单击链接以更改div文本,但在单击另一个链接时需要原始内容 - js

时间:2018-02-13 02:56:56

标签: javascript jquery

我需要在点击时更改Div的文字,但我还需要通过点击其他链接来取回div的原始内容。

我该怎么做?



$(document).ready(function() {
  $('#changeText').click(function() {
    $('#content').text("This is text changed using jquery");
  });
});

#content {
  padding: 10px;
  background: #eee;
  width: 300px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" id="changeText">Click here to change text of div</a>
<a href="#" id="changeText2">Original Div content</a>
<div id="content">
  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

您必须为#changeText2

创建另一个事件

一种方法是将#content的原始内容存储到变量中。如果要还原文本,可以使用变量。

var orginalText = ""; /* Variable to store the original content */

$(document).ready(function(){
    $('#changeText').click(function(){
         orginalText = $('#content').html(); /* store the original content to the variable */
         $('#content').html("This is text changed using jquery");
    });

    $('#changeText2').click(function(){
         if ( orginalText != "" ) $('#content').html(orginalText); /* use the variable to revert the contentn */
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#" id="changeText">Click here to change text of div</a>
<a href="#" id="changeText2">Original Div content</a>
<div id="content">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
</div>

没有变量。使用.data()

$(document).ready(function() {
  $('#changeText').click(function() {
    $('#content').data("orginal-content", $('#content').html());
    $('#content').html("This is text changed using jquery");
  });

  $('#changeText2').click(function() {
    $('#content').html($('#content').data("orginal-content"));
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#" id="changeText">Click here to change text of div</a>
<a href="#" id="changeText2">Original Div content</a>
<div id="content">
  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
</div>