gpt4 book ai didi

javascript - 我无法使用脚本/函数获取标签内容

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

我遇到了一个荒谬的问题(我认为)。我只是无法使用 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>

请问有人可以帮我吗?谢谢。

最佳答案

您正在尝试获取 valuep元素,但是p元素没有 value属性(property)。只有表单字段可以。在其开始和结束标记之间包含文本的非表单字段具有 .textContent .innerHTML 可用于获取/设置其内容的属性。

如果你想给用户一个输入一些数据的地方,你需要创建一些input表单字段,然后您必须等到他们完成此操作才能尝试获取值。

接下来,您有智能引号 “”而不是直引号 ""这可能会导致编码问题。确保您在编辑器中编写代码时不会对代码应用任何格式。有很多很棒的free web editors 就在那里。

您还引用了.css使用完整的本地路径创建文件,这在您稍后部署此代码时将不起作用。您应该使用 relative paths 引用属于系统一部分的文件。

最后,您在 meta 中使用了一些旧的 HTML 语法。 , linkscript标签,因此请注意下面代码片段中的现代版本。

<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>

关于javascript - 我无法使用脚本/函数获取标签内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48631241/

25 4 0