You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何这段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.GetElementById is incorrect. The correct method name is document.getElementById (note the lowercase g).
  • Passing the wrong value to your function: You're passing the entire <input> element to ChangeCookie() instead of the text value inside it. The function expects a string username, so you need to access the .value property of the input.
  • Invalid quote nesting in the onsubmit attribute: Your onsubmit handler 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:03:46