取消隐藏 div 然后在页面重新加载后保留 div



我有一个jquery脚本,当从选择下拉列表中进行选择时,它会显示div。它工作正常,但我想知道如何在页面重新加载后将div 保留在页面上。这是脚本:

$(document).ready(function() {
  $("select").change(function() {
    var color = $(this).val();
    if (color == "Yes") {
      $(".box").not(".Yes").hide();
      $(".Yes").show();
    } else if (color == "No") {
      $(".box").not(".No").hide();
      $(".No").show();
    } else {
      $(".box").hide();
    }
  });
});
<div>
Is this to be a subdomain?<select name="setweb">
      
		<option selected disabled>Please Select</option>
        <option value="Yes">Yes</option>
        <option value="No">No</option>
    </select>
</div>
<br />
<div class="Yes box" style="display:none">
<input type='text' class='text' name='business' size='20' />Enter your subdomain in the text box.

</div>
<div class="No box" style="display:none">
<input type='text' class='text' name='business' size='20' />Enter your domain in the text box.
</div>

<br/>

谢谢你的帮助。

使用本地存储

$(document).ready(function() {
	if(localStorage.getItem("elementToShow")) {
  	$(localStorage.getItem("elementToShow")).show();
  }
  $("select").change(function() {
    var color = $(this).val();
    if (color == "Yes") {
      $(".box").not(".Yes").hide();
      localStorage.setItem("elementToShow", ".Yes");
      $(".Yes").show();
    } else if (color == "No") {
      $(".box").not(".No").hide();
      localStorage.setItem("elementToShow", ".No");
      $(".No").show();
    } else {
      $(".box").hide();
    }
  });
});
<div>
Is this to be a subdomain?<select name="setweb">
      
		<option selected disabled>Please Select</option>
        <option value="Yes">Yes</option>
        <option value="No">No</option>
    </select>
</div>
<br />
<div class="Yes box" style="display:none">
<input type='text' class='text' name='business' size='20' />Enter your subdomain in the text box.

</div>
<div class="No box" style="display:none">
<input type='text' class='text' name='business' size='20' />Enter your domain in the text box.
</div>

<br/>

您可以使用 Cookie 在页面重新加载中存储一些数据。没有其他简单的解决方案...

另请参阅 https://www.w3schools.com/js/js_cookies.asp

您可以在更改时设置 Cookie

document.cookie = "select=somevalue"

然后

$(document).ready(function () {
    var select = document.cookie.split(";")[0] ? document.cookie.split(";")[0].split("=")[0] : null
    if (select) {
        // manually trigger the change
    }
})

编辑 1

"没有其他简单的解决方案......"除了本地存储:D @Nidhin钱德兰

最新更新