为另一个HTML类设置选择选项

Set Selected Option for Another HTML Class

本文关键字:选择 选项 设置 另一个 HTML      更新时间:2023-09-26

如何在加载另一个页面之前为该页面设置所选选项?

假设我有A页和b页。
如果用户点击页面a上的一个按钮,它会将页面B中的一个默认选项更改为"某事",然后它会将用户带到页面B(所以我希望它在页面B加载之前改变)。

如果你设置使用纯JS HTML,没有后端语言,你可以尝试使用GET变量。

Page 1 HTML:

<a href="p2.html?v=1">Option 1</a><br />
<a href="p2.html?v=2">Option 2</a><br />

P2 HTML:

<form>
  <input id="Option1" type="radio" name="Option" value="1">Option 1 </input>
  <input id="Option2" type="radio" name="Option" value="2">Option 2 </input>
</form>

Page 2 JS:

var queryDict = {}
location.search.substr(1).split("&").forEach(function(item) {queryDict[item.split("=")[0]] = item.split("=")[1]})  //Parse GET Params
document.getElementById("Option" + queryDict["v"]).checked = true;  //Set Option checked

我将使用JavaScript的localStorage()对象。那么,在A页上,你可以这样写:

$(document).ready(function(){
    $('a.PageALink').click(function(){
        localStorage.setItem("PageAValue", $(this).text()); // Or use the data attribute, if you want the stored value to be something else, e.g. <a data-value="value to store" href="somewebsite.com">link text</a>
});

然后在B页:

$(document).ready(function(){
    $('a.PageBLink').text(localStorage.PageAValue);
});

当然,这个答案假设您的页面已经包含了jQuery,或者您知道如何包含它。如果这不适合您,请告诉我们您在依赖项和/或脚本方面的限制是什么。