目前我正在尝试以下方法:
现在我有两个带有独特文本的危害,这两个文本都被翻译成其他东西。现在,当我恢复原始文本时,它会同时显示两种危害。你可以在这里看到我的小提琴: https://jsfiddle.net/qhqyro12/1/
<div>
<p class="harms">This is a first test</p>
<p id="test" class="harms">This is a second test</p>
<a id="edit">edit</a>
<a id="revert">revert</a>
</div>
$(function() {
var myOldContent = $(".harms").text();
$('#edit').click(function() {
$('.harms').text('I want this to revert back to original state.');
});
$('#revert').click(function() {
$(".harms").text(myOldContent);
});
});
如何确保将正确的字符串放回正确的.harms中 感谢。
答案 0 :(得分:3)
您可以使用jQuery.data()
存储每个harms
的原始内容
点击edit
后,您的原始数据会存储在数据中,当您点击revert
时,其值就会恢复。
// Implementation:
var originalContentDataAttributeName = "originalContent";
function setRevertableText($el, text) {
$el.data(originalContentDataAttributeName, $el.text());
$el.text(text);
}
function revertText($el) {
// You may want to check for data attribute existence here
$el.text($el.data(originalContentDataAttributeName));
$el.removeData(originalContentDataAttributeName);
}
// Usage:
$("#edit").click(function() {
$(".harms").each(function() {
setRevertableText($(this), "I want this to revert back to original state.");
});
});
$("#revert").click(function() {
$(".harms").each(function() {
revertText($(this));
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<p class="harms">This is a first test</p>
<p id="test" class="harms">This is a second test</p>
<a id="edit">edit</a>
<a id="revert">revert</a>
</div>
&#13;
答案 1 :(得分:1)
您应该在编辑之前先保存旧文本:
$(function() {
var myOldContent;
$('#edit').click(function() {
myOldContent = $('.harms').text();
$('.harms').text('I want this to revert back to original state.');
});
$('#revert').click(function() {
$(".harms").text(myOldContent);
});
});
答案 2 :(得分:0)
$('#edit').click(function(){
$('.hurms').each(function(i, elem){
elem = $(elem);
elem.attr('prev-content', elem.text());
elem.text('you template text');
});
});
$('#revert').click(function(){
$('.hurms').each(function(i, elem){
elem = $(elem);
elem.text(elem.attr('prev-content'));
});
});
这应该有效
答案 3 :(得分:0)
您可以将旧值存储在data
中。然后在单击“还原”时再次检索它。
$(function() {
$('#edit').click(function() {
$('.harms').each(function(){
$this = $(this);
// Store the current text in data old.
$this.data('old', $this.text());
// Set the new text.
$this.text('I want this to revert back to original state.');
});
});
$('#revert').click(function() {
$('.harms').each(function(value, index){
$this = $(this);
// Fetch the old text from data.
var old = $this.data('old');
// Set the text on the element.
$this.text(old);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<p class="harms">This is a first test</p>
<p id="test" class="harms">This is a second test</p>
<a id="edit">edit</a>
<a id="revert">revert</a>
</div>