为何这段JavaScript在HTML中无法运行却能在控制台正常工作?
Let's walk through the problems in your code that are stopping the cookie from setting when the form is submitted — there are a few straightforward fixes needed:
Key Issues in Your Original Code
- Case-sensitive DOM method error: JavaScript is case-sensitive, and
document.GetElementByIdis incorrect. The correct method name isdocument.getElementById(note the lowercaseg). - Passing the wrong value to your function: You're passing the entire
<input>element toChangeCookie()instead of the text value inside it. The function expects a string username, so you need to access the.valueproperty of the input. - Invalid quote nesting in the
onsubmitattribute: Youronsubmithandler uses double quotes inside double quotes (onsubmit="return ChangeCookie(document.GetElementById("user"))"), which breaks the HTML attribute syntax. You need to use single quotes for the inner string, or escape the double quotes.
Corrected Code
Here's the fixed version of your code with all issues addressed:
<?php $cookie_name="user"; $cookie_value="anony"; setcookie($cookie_name, $cookie_value, time() + (86400 * 7), "/"); ?> <script> function ChangeCookie(loginuser){ document.cookie = "user="+ loginuser +"; expires=Thu, 18 Dec 2018 12:00:00 UTC; path=/"; return 1; } </script> <html> <head> <title>Login</title> </head> <body> Please enter your username <form name="myForm" action="/index.html" onsubmit="return ChangeCookie(document.getElementById('user').value)" method="post"> <input type="text" id="user"> <input type="submit" value="Submit"> </form> </body> </html>
Why the Console Test Worked
When you ran the ChangeCookie function directly in the console, you were likely passing a string value (like ChangeCookie("myUsername")), which skips the broken DOM element lookup and quote syntax issues present in your form's onsubmit handler. That's why the cookie set successfully in that scenario.
内容的提问来源于stack exchange,提问作者Leon Gamerman171 Zhang
相关产品推荐
相关产品推荐

