我有一个荒谬的问题(我认为)。我无法使用Script / Function / document.getElementById获取标记内容。用于查看变量(wM)内容的警报始终为空白。我在网上看了很多例子,所有这些例子都很相似,有时就像我的代码一样。见下文:
<!DOCTYPE html>
<html lang ="pt-br">
<head>
<title> loginServlet2 </title>
<meta http-equiv = ”Content-Type” content=”text/html; charset=UTF-8”>
<link rel="stylesheet" type="text/css" href="c:/java/html/css/estilo.css"/>
<script type="text/javascript">
function oMsg()
{
var wM = document.getElementById("wMsgB").textContent;
// var wM = document.querySelector("span").textContent;
alert("wM = "+ wM);
if (wM == "Teste OK!")
{
// document.getElementById("wMsgA").innerHTML = "Test is OK";
document.getElementById("wMsgA").textContent = "Test is OK";
}
else
{
alert("Test is not OK. Before set new msg");
document.getElementById("wMsgA").textContent = "Test is not OK";
}
}
</script>
</head>
<body>
<h2> Login Page2 </h2>
<p>Please enter your username and password</p>
<form method="GET" action="loginServlet2">
<p id="test2"> Username <input type="text" name="userName" size="50"> </p>
<p> Password <input type="password" name="password" size="20"> </p>
<p> <input type="submit" value="Submit" name="B1" onclick="oMsg()"> </p>
</form>
<h3> MsgB : <span id="wMsgB"<%=request.getAttribute("wMsg")%></span></h3>
<p> MsgA : <span id="wMsgA"> </span> </p>
</body>
</html>
是的,有人可以帮帮我吗?感谢。
答案 0 :(得分:1)
您正在尝试获取value
元素的p
,但p
元素不具有value
属性。只有表单字段。在开始和结束标记之间包含文字的非表单字段包含 .textContent
和 .innerHTML
属性,可用于获取/设置其内容。
如果您想为用户提供输入某些数据的位置,则需要创建一些input
表单字段,然后您必须等到他们完成该操作后再尝试获取值
接下来,您有智能引号“”
而不是直引号""
,这可能会导致编码问题。确保在编辑器中编写代码,该编辑器不对代码应用任何格式。那里有很多很棒的 free web editors 。
您还可以使用完整的本地路径引用.css
文件,以后稍后部署此代码时该路径无效。您应该使用 relative paths 来引用属于您系统的文件。
最后,您在meta
,link
和script
标记中使用了一些旧的HTML语法,因此请注意下面代码段中现有版本的现代版本。
<head>
<title>loginServlet2</title>
<meta charset=UTF-8”>
<link rel="stylesheet" href="c:/java/html/css/estilo.css"/>
<script>
function oMsg() {
var wM = document.getElementById("wMsg").textContent;
alert("wM = " + wM);
if (wM == "Test OK!") {
document.getElementById("wMsgA").textContent = "Test is OK";
} else {
alert("Test is not OK. Before set new msg");
document.getElementById("wMsgA").textContent = "Test is not OK";
}
}
</script>
</head>
<body>
<h2> Login Page2 </h2>
<p>Please enter your username and password</p>
<form method="GET" action="loginServlet2">
<p id="test2"> Username <input type="text" name="userName" size="50"> </p>
<p> Password <input type="password" name="password" size="20"> </p>
<p> <input type="submit" value="Submit" name="B1" onclick="oMsg()"> </p>
</form>
<h2>MsgB : <span id="wMsg"><%=request.getAttribute("wMsg")%></span> </h2>
<p>MsgA : <span id="wMsgA"> </span> </p>
&#13;