简体   繁体   English

在页面之间来回切换时,它保留输入值,但不保留jQuery设置的文本

[英]When going back and forth between pages it keeps input value but not text set by jQuery

I have a page with an empty text input, an empty span and the following code: 我有一个页面,其中有一个空的文本输入,一个空的跨度和以下代码:

$('input').on('input', function(){
    $('span').text(this.value);
});

When I type in the input the same text appears in the span. 当我输入输入内容时,跨度中会出现相同的文本。 But when I go to another page in the same browser tab and then go back again, the input field is still filled in, but now the span is empty. 但是,当我在同一浏览器选项卡中转到另一个页面,然后再次返回时,输入字段仍然填写,但是现在范围为空。

How can I make it so that when you go back to the page the span keeps the value of the input? 我如何做到这一点,以便当您返回页面时,跨度保持输入的值?

Thanks! 谢谢!

Edit: I think I've found the solution. 编辑:我想我已经找到了解决方案。

$('input').on('input', function(){
    $('span').text(this.value);
}).not(function(){
    return this.value == '';
}).trigger('input');

The behavior you are experiencing is normal if you are returning to the page by hitting the "back" button or browsing from your local hard drive - - you are seeing the cached version of the page in that case. 如果您通过单击“后退”按钮或从本地硬盘驱动器返回页面,则遇到的现象是正常的-在这种情况下,您将看到页面的缓存版本。 Form fields can cache their values, but a span doesn't have a "value" per se, it has content and that content isn't cached. 表单字段可以缓存其值,但是span本身不具有“值”,它具有内容并且该内容未被缓存。

If you were to return to the page by clicking a link or typing an address (things that cause an HTTP request), the text field will not show the last value from the previous time, it will show its default value. 如果要通过单击链接或键入地址(导致HTTP请求的内容)返回页面,则文本字段将不会显示上一次的最后一个值,而是显示其默认值。

In addition to the code you already have, you just need a script that fires off as soon as the page is ready that resets the span to the value of the input . 除了已有的代码外,您只需要一个脚本,该脚本将在页面准备好后立即触发,将span重置为input的值。

// You must already have a document.ready event handler, so just add to that:
$(function(){

  // This will restore the span's content to the value of the textbox
  $('span').text($('input').val());

  // This is your original code that wires up the textbox to a click
  // event handler
  $('input').on('input', function(){
    $('span').text(this.value);
  });

});

I tend to bind window.popstate(); 我倾向于绑定window.popstate();

$(window).on("popstate", function (e) {
        //code to refill the span goes here.
});

I use it to deserialize a potentially changed querystring, but you could likely use it here to the same effect. 我使用它来反序列化可能更改的查询字符串,但您可能会在这里使用它以达到相同的效果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM