简体   繁体   English

将更改的HTML保存到Javascript变量?

[英]Save changed HTML to a Javascript variable?

If I have a HTML code with for example an input field inside it like this: 如果我有一个HTML代码,例如其中有一个输入字段,则如下所示:

<div><input type="text" name="search_word" value=""></div>

And then a website visitor types something into it, for example Car , without submitting the field or anything, but so the current HTML code looks like this: 然后,网站访问者在其中输入了某些内容,例如Car ,而没有提交该字段或其他任何内容,但是当前的HTML代码如下所示:

<div><input type="text" name="search_word" value="Car"></div>

Can I somehow store this HTML code to a Javascript variable WITH the word Car or whatever is typed in the input field? 我能以某种方式将此HTML代码存储到Java变量中吗? The point is to store the HTML code as it looks for the moment. 关键是暂时存储HTML代码。 The input field was just an example. 输入字段只是一个示例。

Thing is that the visitor can go to another tab in this section of the website and then get back to this tab. 事实是,访问者可以转到网站此部分中的另一个选项卡,然后返回到该选项卡。 My idea is that the HTML will be retrieved from the Javascript variable. 我的想法是从Javascript变量中检索HTML。

I've noticed that it doesn't work with just $('.search-form').html() . 我注意到,它不仅仅与$('.search-form').html() That will just store the original version of the HTML. 那将只存储HTML的原始版本。

I understand it's possible to just let the HTML be left in the code with a "hidden" style-rule or something. 我知道有可能只是将HTML留在代码中,并保留“隐藏”的样式规则或其他内容。 But I would mostly like to have it stored as a Javascript variable for performance reasons. 但是出于性能原因,我主要希望将其存储为Javascript变量。

You could try using web storage, take a look at this link Web storage (W3Schools) 您可以尝试使用Web存储,看看此链接Web存储(W3Schools)

You can store data in the browser and use it later on. 您可以将数据存储在浏览器中,以后再使用。

To save on code repeating, you can do something like this 为了节省代码重复,您可以执行以下操作

<input type="text" name="product" onchange="TextChanged(this.name, this.value)">
<input type="text" name="product1" onchange="TextChanged(this.name, this.value)">
<input type="text" name="product2" onchange="TextChanged(this.name, this.value)">

<script type="text/javascript">
  TextChanged = (name, value) =>
  {
      if(localStorage[name] == null)
      {
          //if the item doesn't exist, create it
          localStorage.setItem(name, value);
      }
      else
      {
          //else modify it
          localStorage[name] = value;
      }
  }
</script>
<input type="text" id="user-input" oninput="captureInput()">

<p id="user-output"></p>

<script>
function captureInput() {

var userInput = document.getElementById("user-input").value;
var elOutput = document.getElementById("user-output");
elOutput.innerHTML = "User Input: " + userInput;
var userOutput = elOutput.innerHTML;    
}
</script>

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

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