1 回答
TA贡献1790条经验 获得超9个赞
您可以单独使用 JS 来完成此操作,但还有许多其他方法。
<body>
<input type='text' value='defaultParamValue'>
<button type='button'>send param</button>
<script type='text/javascript'>
document.querySelector('button').onclick
= () => window.location.href
= 'destination.html?nameOfParam='
+ encodeURIComponent(document.querySelector('[type=text]').value)
</script>
</body>
你可以用PHP来做到这一点,更现实和实用。
<body>
<form action='destination.php' method='get'>
<input name='param' type='text' value='defaultParamValue>
<input type='submit'>
</form>
</body>
这就是您使用 PHP 在 处检索值的方式destination.php。
$_POST['param'];
以下是如何使用您自己的示例进行操作。
<body>
The on/off button:
<!-- you need to include type='button', otherwise it acts as type='submit' -->
<button type='button' onclick='press_button()'>
<img id='button' src='on.png' style='width:100px'>
</button>
<BR>
The button that opens a new webpage:
<!-- you need to include type='button', otherwise it acts as type='submit' -->
<button type='button' onclick='confirm()'> Confirm</button>
<script type='text/javascript'> // the language attribute is deprecated
var
i=0,
button=document.querySelector('button'),
status
function press_button(){
i++
if(i%2 == 1){
button.src='off.png'
status=true
}
else{ // you were missing a curly bracket
button.src='on.png'
status=false
}
} // you were missing a closing curly bracket
function confirm(){
if(status){
// window in window.open is a global variable
// which means it is always accessible
// and you do not need to include it
open(`confirm.html?status=${encodeURIComponent(status)}`)
}
} // you were missing a closing curly bracket
</script>
</body>
构建代码可以更容易地发现代码中的问题(即缺少大括号)。
下面的 JS 将允许您在新页面上获取 URL 查询字符串参数。
const
urlParams = new URLSearchParams(location.search),
myParam = urlParams.get('status')
console.log(urlParams) // status=true/false
console.log(myParam) // true/false
添加回答
举报