【问题标题】:Reseting the changes of paragrapgh重置段落的更改
【发布时间】:2019-05-02 19:56:17
【问题描述】:

我正在努力显示跨度中发生的更改段落。最初,这是 HTML 的代码。

<div>
   <p><span id="spnOne">This text will change.</span></p>
</div>

我把原文改成:

Text Before ++ Text at the front --Span 的新文本 == 后面的文本@@Text After 通过使用 append、prepend、before 和 after。

我有这个按钮。

<div>
   <button id="btnResetChanges">Reset Paragraph Text</button>
</div>

当我单击此按钮时,我想更改发生的所有更改,使其恢复到原始状态。

我试过了

$("#btnResetChanges").click(function () {
  ($("#spnOne").reset());

}); 

【问题讨论】:

  • reset() 不是 jQuery 方法。这是一种本机方法,旨在重置表单字段。段落不是表单域。如果你想“重置”一个段落,你将不得不自己跟踪原始值,并自己进行重置。
  • @Taplar 你能帮我举个例子吗?那真的很棒
  • @Taplar 是正确的。您应该使用local storage 之类的方法来存储原始段落 - 这是使用local storage stackoverflow.com/questions/40791207/… 的精彩读物
  • 您应该将值存储在本地参数中,然后在 javascript 或 jquery 中将其重置,我认为没有任何 API 可以重置它。
  • 最简单的方法是将段落中的原始值存储为数据字段。没有理由将其放入 localStorage 并使其变得更加全球化。

标签: jquery


【解决方案1】:

//if you don't want to preload the data fields in the html
//you can set them with the javscript
var $changable = $('.changable').each(function(){
  $(this).data('originalHtml', this.innerHTML);
});

//when the button is clicked, change all the fields back to what is
//in their original data field
$('#btnResetChanges').on('click', function(){
  $changable.html(function(index, element){
    return $(this).data('originalHtml');
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <p><span class="changable" contenteditable="true">This text will change.</span></p>
  <p><span class="changable" contenteditable="true">This text will change.</span></p>
  <p><span class="changable" contenteditable="true">This text will change.</span></p>
</div>


<div>
  <button id="btnResetChanges">Reset Paragraph Text</button>
</div>

【讨论】:

    【解决方案2】:

    在这种情况下,您可以使用 cookie 和本地存储,但我建议您使用 data-* attributes 存储原始段落,然后在您想要重置时调用它,例如:

    $('#spnOne').append('++++').prepend('----');
    
    $('#btnResetChanges').click(function() {
      $('#spnOne').text($('#spnOne').data('original'));
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div>
      <p><span id="spnOne" data-original="This text will change.">This text will change.</span></p>
    </div>
    <div>
      <button id="btnResetChanges">Reset Paragraph Text</button>
    </div>

    【讨论】:

      猜你喜欢
      • 2017-05-06
      • 1970-01-01
      • 1970-01-01
      • 2018-01-26
      • 2011-09-02
      • 2016-07-05
      • 2013-10-27
      • 2010-09-24
      • 1970-01-01
      相关资源
      最近更新 更多