我有一个下拉菜单可以选择使用的货币。一旦做出选择,页面就会以所选货币重新加载。我希望货币选择的“标题”标签显示在新打开的网页的文本区域中。我有在现有打开的页面中添加“标题”标签的代码,但这不会将其放入新加载页面的文本区域中。这可能吗?
如果可能的话,当用户刷新新网页时,文本区域中的内容会被记住/调用。
这是两个问题,知道其中一个的答案后,请不要犹豫。
到目前为止我的代码:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<form name="currency select" title="Currency Selector">
<select name="currency" id="currencyList" onchange="window.document.location.href=this.options[this.selectedIndex].value;" value="GO">
<option value="" disabled="disabled" selected="selected" none="">$ € £</option>
<option value="/session/currency/usd/" title="US Dollar">USD</option>
<option value="/session/currency/eur/" title="EURO">EUR</option>
</select>
<textarea id="showTitle"></textarea>
</form>
</body>
<script>
$(document).ready(function()
{
$(document).on('change','#currencyList',function()
{
var result = $("option:selected",this).attr('title');
$("#showTitle").text(result);
});
});
</script>
最佳答案
我终于弄清楚了问题所在,这是由于直接附加在重定向页面的下拉列表上的 onchange
脚本造成的(我现在已将其注释掉)。当下拉列表更改时, session 数据也没有更新。尝试一下这段代码:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<form name="currency select" title="Currency Selector">
<select name="currency" id="currencyList" value="GO">
<option value="" disabled="disabled" selected="selected" none="">$ € £</option>
<option value="/session/currency/usd/" title="US Dollar">USD</option>
<option value="/session/currency/eur/" title="EURO">EUR</option>
</select>
<textarea id="showTitle"></textarea>
</form>
<script>
$(document).ready(function(){
var field = document.getElementById("showTitle");
var savedValue = sessionStorage.getItem("autosave");
// See if we have an autosave value
// (this will only happen if the page is accidentally refreshed)
if (savedValue) {
// Restore the contents of the text field
field.value = savedValue;
//set dropdown to session value
$('#currencyList option[title="'+ savedValue + '"]').prop('selected', true);
}
// Listen for changes in the text field
field.addEventListener("input", function() {
// And save the results into the session storage object
sessionStorage.setItem("autosave", this.value);
});
$(document).on('change','#currencyList',function(){
//get text
var result = $("option:selected",this).attr('title');
//set field
$(field).val(result);
//set session storage item
sessionStorage.setItem("autosave", result);
//redirect
window.document.location.href=this.options[this.selectedIndex].value;
});
});
</script>
</body>
</html>
关于javascript - 如何使(下拉)操作发生在新加载的页面上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36047839/