Javascript document.getElementById

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7699485/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:13:47  来源:igfitidea点击:

document.getElementById

javascript

提问by swydell

I'm working on an assignment in my beginner Javascript class that involves an element document.getElementById on the first line below the var total. There is an error of missing ";" but the semicolon is there. So I know that it must be something else. Here is the code. Any suggestions?

我正在我的初学者 Javascript 课程中进行一项作业,该课程涉及 var 总数下方第一行的元素 document.getElementById。有遗漏“;”的错误 但分号在那里。所以我知道它一定是别的东西。这是代码。有什么建议?

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Price Calculator</title>
<script type="text/javascript">
function fixOrder(){
const TAX = 0.975;
var numPrice = parseFloat(document.getElementById("cost").value);


var subtotal = numPrice * TAX;
var total = subtotal + tax;
document.getElementById("cost").value = "$" cost.ToFixed(2);
document.getElementById("tax").value ="$" tax.ToFixed(2);
document.getElementById("total").value ="$" total.ToFixed(2);
}

function placeOrder(){
if (document.getElementById("cost") == ""
isNaN(document.getElementById("cost")
alert("Sorry,you must enter a numeric value to place order")
if (document.getElementById("tax") == ""
isNaN(document.getElementById("tax")
alert("Sorry, you must enter a numeric value to place the order");
}
</script>

</head>

<body bgcolor="#00f3F1">
<frame align="left">
<legend>
<h1 align="center">Price Calculator</h1>
</legend>
<form name="purchases" action="donut.php"  method="POST">

Price:<p> <input type="text" id="cost" name="cost" value="" onchange="fixOrder">
</p>
Tax:<p>  <input type="text" id="tax" name="tax" value="" onchange="fixOrder">
</p>
Total:<p> <input type="text" id="total" name="total" value="" >
</p>
</form>
</frame>



<div id="cost" name="cost" value="" onchange="placeOrder();"></div>
</body>
</html>

采纳答案by James Allardice

As has already been pointed out by the numerous other answers, there are a multitude of problems with your code. This answer is intended to address all of the mistakes and shortcomings.

正如许多其他答案所指出的那样,您的代码存在许多问题。这个答案旨在解决所有错误和缺点。

I'll go from the top of the posted code. Firstly, you may have simply not pasted it into the question, but you're missing a DOCTYPEdeclaration at the top of the file. All HTML documents should begin with a DOCTYPE, for example:

我将从已发布代码的顶部开始。首先,您可能只是没有将其粘贴到问题中,但是您缺少DOCTYPE文件顶部的声明。所有 HTML 文档都应以 开头DOCTYPE,例如:

<!DOCTYPE html>

<!DOCTYPE html>

Into the JavaScript, the constkeyword, while valid, is not supported by a lot of older browsers and is definitely best avoided. Replace it with var, it will make no difference.

在 JavaScript 中,该const关键字虽然有效,但很多旧浏览器不支持,因此最好避免使用。将其替换为var,它不会有任何区别。

To concatenate strings in JavaScript you use the +operator:

要在 JavaScript 中连接字符串,请使用+运算符:

document.getElementById("cost").value = "$" + cost.toFixed(2);

document.getElementById("cost").value = "$" + cost.toFixed(2);

Also notice that I've changed ToFixedto toFixed. Another problem with the above line is the variable cost, which you've not defined. You may have meant numPrice, but I'm not entirely sure!

另请注意,我已更改ToFixedtoFixed. 上一行的另一个问题是cost您尚未定义的变量。你可能是这个意思numPrice,但我不完全确定!

On the next line, you're using taxinstead of TAX. Variable names in JavaScript are case-sensitive, so taxis also undefined.

在下一行,您使用的是tax而不是TAX。JavaScript 中的变量名区分大小写,因此tax也是未定义的。

Your ifstatement conditions are wrong. I'm assuming you meant this:

你的if语句条件是错误的。我假设你的意思是:

if(document.getElementById("cost").value == "" || isNaN(document.getElementById("cost").value)

There's a few changes to that line. Firstly, you were comparing a DOM element itself (getElementByIdreturns a DOM element), rather than the value of it. Secondly, you were missing the closing parentheses, and finally, you needed some operator between the two conditions. I think you were after the "or" operator, ||. There's a similar issue with your second ifstatement.

那条线有一些变化。首先,您比较的是 DOM 元素本身(getElementById返回一个 DOM 元素),而不是它的值。其次,您缺少右括号,最后,您需要在两个条件之间使用一些运算符。我认为您是在“或”运算符之后,||. 你的第二个if陈述也有类似的问题。

You're missing a semi-colon off the end of your first alertline. While that's still valid, it's definitely good practice to always include the semi-colon.

您在第一alert行的末尾缺少一个分号。虽然这仍然有效,但始终包含分号绝对是一个好习惯。

Back into the HTML, you're trying to call the fixOrderJS function, but you've missed the parentheses:

回到 HTML,您正在尝试调用fixOrderJS 函数,但是您错过了括号:

<input type="text" id="cost" name="cost" value="" onchange="fixOrder()">

To be really picky, you shouldn't really use inline event handlers, but I won't go into that here.

说真的,你不应该真正使用内联事件处理程序,但我不会在这里讨论。

I'm not sure why you're using a frameelement the way you are, but I have a feeling it would be better replaced by a div, or simply nothing at all (again, I may not have the full picture if you haven't posted the full code).

我不知道你为什么像现在这样使用frame元素,但我觉得用 a 代替它会更好div,或者干脆什么都不用(同样,如果你没有,我可能没有完整的图片贴出完整代码)。

On your bodytag you're using the bgcolorattribute. That should definitely be replaced by CSS. You can use the background-colorproperty.

在您的body标签上,您正在使用该bgcolor属性。那绝对应该被CSS取代。您可以使用该background-color物业。

回答by Vivin Paliath

You need to use a concatenation operator here (notice the +):

您需要在此处使用连接运算符(注意+):

document.getElementById("cost").value = "$" + cost.ToFixed(2);

You also have syntax errors in your ifstatement. They should be:

您的if语句中也有语法错误。他们应该是:

if (document.getElementById("cost") == "" || isNaN(document.getElementById("cost")) {
   ...
}

and

if (document.getElementById("tax") == "" || isNaN(document.getElementById("tax")) {
   ...
}

Also, please consider indenting your code. It makes it much easier to read and maintain and will help you spot your syntax errors much more easily as well.

另外,请考虑缩进您的代码。它使阅读和维护变得更加容易,并且还可以帮助您更轻松地发现语法错误。

There are a few other errors (not syntax), but I will let you figure those out; this is homework after all.

还有一些其他错误(不是语法),但我会让你弄清楚;毕竟这是家庭作业。

EDIT: It looks like you're a real beginner, so in addition to what you're learning in class, I'd pick up some books that are tailored for beginners. Here are some that I was able to find.

编辑:看起来你是一个真正的初学者,所以除了你在课堂上学到的东西之外,我还会挑选一些为初学者量身定制的书籍。以下是我能找到的一些内容

回答by Eric

In javascript, you concatenate strings with the +operator. Instead of

在 javascript 中,您将字符串与+运算符连接起来。代替

document.getElementById("cost").value = "$" cost.ToFixed(2);

Use

document.getElementById("cost").value = "$" + cost.ToFixed(2);


Your if statements are also wrong. Instead of

你的 if 语句也是错误的。代替

if (document.getElementById("cost") == ""
isNaN(document.getElementById("cost")
alert("Sorry,you must enter a numeric value to place order")

Use

if(isNaN(document.getElementById("cost").value))
    alert("Sorry,you must enter a numeric value to place order");

回答by Ry-

You're missing +between "$"and the xxx.ToFixed(2)s. What's more, it's toFixed, not ToFixed. You're also missing closing parenthesis everywhere (ifstatements and isNaNcalls) as well as a ||between the two.

+"$"xxx.ToFixed(2)s之间丢失了。更何况是toFixed,不是ToFixed。您还缺少处处(if语句和isNaN调用)以及||两者之间的右括号。

回答by Jason Gennaro

A few things here:

这里有几件事:

  1. you should optimize the code by setting variables for your document.getElementById("cost"). So var c = document.getElementById("cost");

  2. your if statementsare missing closing parentheses and oroperators.

    if (document.getElementById("cost") == "" isNaN(document.getElementById("cost")

  1. 您应该通过为您的document.getElementById("cost"). 所以var c = document.getElementById("cost");

  2. if statements缺少右括号和or运算符。

    if (document.getElementById("cost") == "" isNaN(document.getElementById("cost")

should be

应该

if (document.getElementById("cost") == "" || 
isNaN(document.getElementById("cost"))

You are also missing a ;after your alert here

;在这里也错过了警报之后

if (document.getElementById("cost") == ""
isNaN(document.getElementById("cost")
alert("Sorry,you must enter a numeric value to place order")

回答by Mahesh Guttedar

<p>if ($(this).attr('name') == 'time') {
    var value = $(this).val();
    parseFloat(value).toFixed(2);
    alert(value);
    editEntry.time = value;
}
</p>

回答by Alessandro Desantis

That code was a total mess. I've fixed it up. It should work now:

那个代码一团糟。我已经修好了。它现在应该可以工作:

function fixOrder()
{
    const TAX = new Number(0.975);

    var numPrice = parseFloat(document.getElementById("cost").value);
    var cost = new Number(document.getElementById("cost").value);
    var total = new Number(document.getElementById("total").value);

    var subtotal = numPrice * TAX;
    var total = new Number(subtotal + TAX);

    document.getElementById("cost").value = "$" + cost.toFixed(2);
    document.getElementById("tax").value ="$" + TAX.toFixed(2);
    document.getElementById("total").value ="$" + total.toFixed(2);
}

function placeOrder()
{
    if (document.getElementById("cost").value == "" || isNaN(document.getElementById("cost").value)) {
        alert("Sorry,you must enter a numeric value to place order");
    }

    if (document.getElementById("tax").value == "" || isNaN(document.getElementById("tax").value)) {
        alert("Sorry, you must enter a numeric value to place the order");
    }
}

回答by K''

There are couple of errors going on here, first, you need to concatenate the string "$" with cost.ToFixed(2); using the concatenation operator +, apply this for the next 2 lines.

这里发生了几个错误,首先,您需要将字符串 "$" 与 cost.ToFixed(2); 连接起来。使用连接运算符 +,将其应用于接下来的 2 行。

Other errors are in the if conditions, you are missing the closing ) in both if conditions, also, I guess that you want to check that the value of the text box is empty so you need to add .value.

其他错误在 if 条件中,您在两个 if 条件中都缺少关闭 ),此外,我猜您想检查文本框的值是否为空,因此您需要添加 .value。

here is the working source

这是工作来源

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Price Calculator</title>
<script type="text/javascript">
function fixOrder(){
const TAX = 0.975;
var numPrice = parseFloat(document.getElementById("cost").value);


var subtotal = numPrice * TAX;
var total = subtotal + tax;
document.getElementById("cost").value = "$" +cost.ToFixed(2);
document.getElementById("tax").value ="$" +tax.ToFixed(2);
document.getElementById("total").value ="$" +total.ToFixed(2);
}

function placeOrder(){
if (document.getElementById("cost").value == "" ||     isNaN(document.getElementById("cost").value))
alert("Sorry,you must enter a numeric value to place order");
if (document.getElementById("tax").value == "" ||     isNaN(document.getElementById("tax").value))
alert("Sorry, you must enter a numeric value to place the order");
}
</script>

</head>

<body bgcolor="#00f3F1">
<frame align="left">
<legend>
<h1 align="center">Price Calculator</h1>
</legend>
<form name="purchases" action="donut.php"  method="POST">

Price:<p> <input type="text" id="cost" name="cost" value="" onchange="fixOrder">
</p>
Tax:<p>  <input type="text" id="tax" name="tax" value="" onchange="fixOrder">
</p>
Total:<p> <input type="text" id="total" name="total" value="" >
</p>
</form>
</frame>



<div id="cost" name="cost" value="" onchange="placeOrder();"></div>
</body>
</html>