首页 > 解决方案 > 如何通过使用jquery单击另一个html页面上的元素来设置一个html页面的输入值?

问题描述

我有 html 页面名称 try1.html

<html>
<head>
    <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"
        integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n"
        crossorigin="anonymous"></script>
</head>
<body>
    <div id="join1">Join1</div>
    <div id="join2">Join2</div>
    <script src="script.js"></script>
</body>
</html>

和另一个 html 页面名称 try2.html

<html>

<head>
    <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"
        integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n"
        crossorigin="anonymous"></script>
</head>

<body>
    <div><input type="text" id="val"></div>
    <script src="script.js"></script>
</body>

</html>

我想根据我选择使用 jquery(script.js) 在 try1.html 中单击的内容,将 try2.html 的输入值设置为不同的值,如下所示:

$(document).ready(function(){
    $("#join1").click(function(){
        $("#val").val("Z1");
        $(location).attr("href", "try2.html");
    });
    $("#join2").click(function(){
        $("#val").val("Z2");
        $(location).attr("href", "try2.html");
    });
});

我是否犯了任何错误导致值不变?谢谢你...

标签: htmljquery

解决方案


您可以使用 GET 参数。

$(document).ready(function(){
$("#join1").click(function(){
    $(location).attr("href", "try2.html?q=Z1");
});
$("#join2").click(function(){
    $(location).attr("href", "try2.html?q=Z2");
    });
});

您也可以更改输入名称。

 <div><input name="q" type="text" id="val"></div>

然后就可以获取参数了。

const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
const ourValue = urlParams.get('q');
console.log(ourValue); //you can change your input value to ourValue.
document.getElementById('val').value = ourValue;

推荐阅读