有人可以解释一下这个JavaScript是如何工作的
Can someone explain how this JavaScript is working?
所以我设法将一些JavaScript放在一起(在其他人的帮助下(,它基本上是一种表单,允许您更改项目的数量,并在勾选其复选框时将其值添加到总数中(总计显示在底部的文本字段中(。
我理解其中的一些,只是其中更复杂的部分让我感到困惑(例如逻辑(。有人可以告诉我,或者也许评论我代码的主要部分,这样它可以帮助我理解代码是如何工作的。
<script type="text/javascript">
function bump( which, bywhat ) {
var form = document.items;
var qty = form["qty" + which];
qty.value = Number(qty.value) + bywhat;
TotalCheckedValues( ); // in case user bumped an already checked line
}
function TotalCheckedValues( ) {
var form = document.items;
var total = 0;
for ( var n = 1; n <= 4; ++n )
{
if ( form["cb"+n].checked ) // if the checkbox of the item is ticked
{
total += form["cb"+n].value * form["qty"+n].value; //
}
}
form.Total.value = total.toFixed(2);
}
function validate(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
var regex = /[0-9]|'./;
key = String.fromCharCode( key );
if(!regex.test(key)) {
theEvent.returnValue = false;
if (theEvent.preventDefault) {
theEvent.preventDefault();
}
}
}
</script>
</head>
<body>
<form name="items">
Item <input type="text" onkeypress='validate(event)'name="qty1" value="0"/>
<input type="button" onclick="bump(1,1)" value="+"/>
<input type="button" onclick="bump(1,-1)" value="-"/>
<input type="checkbox" name="cb1" value="20.00"
onClick="TotalCheckedValues()" />Service 1 (£20.00) <br />
Item <input type="text" onkeypress='validate(event)' name="qty2" value="0"/>
<input type="button" onclick="bump(2,1)" value="+"/>
<input type="button" onclick="bump(2,-1)" value="-"/>
<input type="checkbox" name="cb2" value="20.00"
onClick="TotalCheckedValues()" />Service 2 (£20.00) <br />
Item <input type="text" onkeypress='validate(event)' name="qty3" value="0"/>
<input type="button" onclick="bump(3,1)" value="+"/>
<input type="button" onclick="bump(3,-1)" value="-"/>
<input type="checkbox" name="cb3" value="20.00"
onClick="TotalCheckedValues()" />Service 3 (£20.00) <br />
Item <input type="text" onkeypress='validate(event)' name="qty4" value="0"/>
<input type="button" onclick="bump(4,1)" value="+"/>
<input type="button" onclick="bump(4,-1)" value="-"/>
<input type="checkbox" name="cb4" value="10.00"
onClick="TotalCheckedValues()" />Service 4 (£10.00) <br />
Total: <input type="text" name="Total" readonly size="5" />
<input type="reset" name="reset" value="Clear Selected">
</form>
</body>
</html>
首先,我不确定这是你应该学习的那种JavaScript......但是,我会尝试给你一些提示
有3个功能:validate
,bump
和TotalCheckedValues
Validate
是最容易理解的。请注意每个 onkeypress
属性中对此函数的调用。调用 Verify 以验证刚刚按下以键入输入的键是介于 0 和 9(包含(之间的数字还是点。(正则表达式检查(
bump
已记录每个项目上 + 和 - 按钮的点击次数(以跟踪数量(。它依赖于对document.items
形式的调用,该形式给出其items
,这些按升序命名,并由其名称中的数字标识(第一项name="qty1"
(。该函数将项目的索引和增加或减少其值的金额作为参数(第 3 项的 + 按钮bump(3,1)
,这意味着:获取第 3 项并在其值上加 1(。该函数以调用第三个函数结束
TotalCheckedValues
可以重新计算总金额(如果选中此项目的复选框,则每个项目的sum(quantity*price)
(。此函数重新排列项目,迭代这些项目,检查复选框是否被选中,如果是,则取价格和数量,将它们相乘并将它们添加到 total
// Also going to be cleaning up the code a little - no offense, I'm just anal
// One more note: I'll be specifying types in my function documentation - but remember
// that JS doesn't really *do* types
/**
* Grab a quantity and increase it by a given value
* @param int which Number of the field to target (comes out as 'qty1/2/3/4/etc')
* @param int bywhat Number to increase the value found with 'which' by
*/
function bump(which, bywhat) {
// Find the form child named 'qtyn', where n is a number
// Notice only one var definition here - no need to define form if
// you can just get to your target element/attribute/etc.
var qty = document.items['qty' + which].value;
qty = Number(qty) + bywhat; // Add bywhat to the form value
TotalCheckedValues(); // in case user bumped an already checked line
}
/**
* Iterate through all check boxes (cb) on the form and multiply quantities (qty)
* against values on checked boxes.
*/
function TotalCheckedValues() {
// Some consider it best practice to put all vars in the top of the method,
// in a comma-separated list using one "var" keyword.
var form = document.items,
total = 0,
checkbox = null,
n = 1;
for(n; n <= 4; ++n)
{
checkbox = "cb"+n; // make your code easier to read
if(form[checkbox].checked) // if the checkbox of the item is ticked
{
// If the checkbox is checked, multiply it's value to that of each qty field
total += form[checkbox].value * form["qty"+n].value;
}
}
form.Total.value = total.toFixed(2); // Shorten 'total' to 2 decimal places
}
/**
* Test for a valid key
* @param event evt The key-related event
*/
function validate(evt) {
/*
* In javascript, the OR operator || is used as a way of setting defaults. So,
* keep trying values until one that's considered "true" is found:
* var something = false;
* var foo = null;
* var bar = 'abc';
* var which = something || foo || bar; // value of 'which' is 'abc'
*/
var theEvent = evt || window.event,
key = theEvent.keyCode || theEvent.which,
regex = /[0-9]|'./; // Regex that matches 0-9 and '.'
key = String.fromCharCode( key ); // Convert from key code to something usable
// I almost think you could do...
// var ... key = String.fromCharCode(theEvent.keyCode || theEvent.which)
// but I'm not sure.
// If our key event's code doesn't pass our regex test
if(!regex.test(key)) {
theEvent.returnValue = false;
if(theEvent.preventDefault)
theEvent.preventDefault();
}
}
其他一些建议
我想分享的其他一些建议,也许只是一些需要考虑的建议:
依赖硬编码的限制(TotalCheckedValues((中for循环中的"4"(会使代码的可重用性降低。相反,您应该遍历所有匹配的子节点到父节点。使用jQuery,它将类似于
$('#MyFormId input[type="checkbox"]).each(...)
这使得代码灵活,并且不需要仅仅因为您添加了另一个复选框而进行更新。在表单元素上使用 ID 以使选择更加明显 - 依靠 document[name] 是可以的,但可能不是在所有地方都能很好地播放。
哪个,bywhat,evt - 变量名称很棒,因为它们可以是任何东西,所以在决定如何称呼变量时请记住这一点。 描述性名称 1( 帮助你记住 2 个月后回到代码时发生了什么,2( 帮助任何其他必须浏览你的代码的人,无论出于何种原因,了解正在发生的事情。
一致性是关键:你的函数名称在风格上是混合的:bumb vs TotalCheckedValues vs validate - 你应该为代码选择一种方法并坚持下去。
有时访问 JSLint 如果你真的想要一些可以挑剔你的代码的东西......让你哭泣。但是,只要阅读"JSLint如何工作?"页面,了解它们如何以及为什么选择代码的某些部分,对于学习Javascript和一些JS的最佳实践©很有价值。
注意:我写了大约一半,发现人们已经回答了 - 对任何重复表示歉意,但我想完成我开始的事情!
1. "凹凸"功能
此函数接受两个参数:
- ">which"是一个数字,有助于识别特定的文本字段。
- ">bywhat"是一个数字,表示字段中的数字要增加/减少多少 - 或者使用此处使用的术语 - "颠簸"。
var form = document.items;
该函数首先获取全局文档对象中的所有项的数组,您可以从任何位置访问这些项。
var qty = form['qty' + which];
然后,此代码尝试访问该数组中的特定项,该数组的名称为"qty"加上 what 参数。在这种情况下,当您使用"+"运算符时,您将字符串("qty"(添加到数字(其中(,最终会得到一个字符串;例如"Qty3"。
qty.value = Number(qty.value( + bywhat;
然后设置"qty+where"输入元素的值,方法是获取当前值,将其转换为数字,然后将 bywhat 参数添加到其中。在这种情况下,当您使用"+"运算符时,您将数字添加到数字中,您将执行数学计算;例如 1 + 2 = 3。
TotalCheckedValues((;
然后,代码调用 TotalCheckedValues 函数,该函数似乎用于计算总数(我们接下来将讨论(。
2. "总检查值"功能
此函数由每个"bump"函数调用后调用,并且每次选中/取消选中复选框时也会调用。
var form = document.items;
该函数再次从获取全局文档对象中的所有项的数组开始,您可以从任何地方访问这些项。
变量总数 = 0;
然后,该函数定义一个设置为零的"total"变量。
"for"循环
然后,代码循环四次,HTML 中的每个输入/按钮/复选框组一次。它尝试获取每个组的复选框元素,然后检查是否选中了该复选框。如果是,则复选框值(即价格(乘以文本字段的数量值,并添加到"总计"变量中。此处的"+="运算符将其右侧的值添加到现有值中,而不是覆盖现有值。
形式。Total.value = total.toFixed(2(;
然后,该函数尝试在 document.items 数组中查找名为"Total"的元素,使用点表示法而不是您之前看到的括号表示法(例如 form['qty'](。该元素的值是使用上述 for 循环生成的总数设置的。toFixed(2( 函数可用于数字, 返回具有给定小数位数的数字的字符串表示形式 - 在本例中为 2。
3. "验证"功能
var theEvent = evt || window.event;
创建一个包含已引发的事件对象的变量。它检查传递的 evt 参数中是否存在事件对象 - 如果为 null 或未定义,则使用 window.event 事件对象。
var key = theEvent.keyCode || theEvent.which;
尝试确定按下了哪个键来触发事件并将其存储在变量中。
var 正则表达式 =/[0-9]|。/;
定义正则表达式模式,该模式将匹配值 0 到 9 以及点字符。
key= String.fromCharCode(key(;
尝试从密钥中检索字符串,这...
if(!regex.test(key((
。然后针对正则表达式进行测试。test(( 函数如果与模式匹配,则返回 true,如果不匹配,则返回 false。如果正则表达式匹配失败,则运行此"if"语句中的其余代码;它设置事件的返回值,并取消事件 (preventDefault(,而不停止将事件传播到其他侦听器。
希望 JavaScript 函数的演练对您有所帮助!
- Zurb基金会's javascript不工作
- Javascript不工作/正在加载
- 只有当Javascript控制台在chrome上打开时,Javascript才能工作
- Num doenst在我的javascript中工作
- 可以't让ClientContext.executeQuery()在javascript中工作
- Javascript setInterval工作不正常
- 没有获得基础's的Javascript元素工作(与Laravel和Elixir)
- 在Alfresco中动态创建空间/文件夹的Javascript;t工作正确
- 我怎样才能让这个javascript正常工作
- 如何使手风琴(CSS+javascript)工作
- 为不在javascript中工作的动态创建类设置属性
- 服务器重新启动后javascript不工作
- function.apply如何在javascript中工作
- 我该怎么做[硬编码号码].[函数调用]在Javascript中工作
- 让PHP、Form和Javascript协同工作
- 我的regex可以在regex101.com沙箱中工作,但不能在实际的javascript中工作
- Check IF条件返回false,但IF中的语句仍然可以在JavaScript中工作
- Javascript 不工作,结果打印后浏览器仍在加载
- 添加两个数字的JavaScript函数工作不正常
- 在CRM 2011中从JavaScript执行工作流