gpt4 book ai didi

javascript - 将变量从 html 内的 JS 代码传递到单独的 JS 代码,不起作用

转载 作者:行者123 更新时间:2023-12-02 17:46:55 25 4
gpt4 key购买 nike

first.html

<!DOCTYPE html>
<html>

</head>

<body>
<form>
<script type="text/javascript">

// grab the id number
var theIdNumber = localStorage.getItem("idNumber");

// set the ID in the HTML page
document.getElementById("userId").value = theIdNumber;
</script>

<button type="button" onClick="validateUsernamePassword()">SEND</button>
</form>
</body>
</html>

other.js

function validateUsernamePassword()
{
var idNum = $("#userId").val();
alert('Well the id is :' + idNum);

// more code
}

警报不打印传递的 ID...为什么?

最佳答案

像这样修改你的html:

<html>
<head>
<title></title>
</head>
<body>
<form>


<button type="button" onClick="validateUsernamePassword()">SEND</button>
<input type="hidden" id="userId"></input>
</form>
<script type="text/javascript">

// grab the id number
var theIdNumber = localStorage.getItem("idNumber");

// set the ID in the HTML page
document.getElementById("userId").value = theIdNumber;
</script>
</body>

</html>

或者你可以这样做:

function validateUsernamePassword()
{
var idNum = localStorage.getItem("idNumber");
alert('Well the id is :' + idNum);

// more code
}

第二个很好,因为您已经在本地存储中拥有该项目,因此无需将其值分配给另一个元素

关于javascript - 将变量从 html 内的 JS 代码传递到单独的 JS 代码,不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21656950/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com