与jquery相乘 [英] Multiplying with jquery
问题描述
我有一个简单的脚本,我想将Var a * Var b乘以然后将Var C乘以设定的数字,例如15.
I have this simple script, i want to multiply Var a * Var b then Multiply this by Var C with a set number eg 15.
但这似乎不起作用吗?
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$('input[name="box2"]').keyup(function() {
var a = $('input[name="box1"]').val();
var b = $(this).val();
var c = $(15).val();
$('input[name="box3"]').val(a * b * c);
});
</script>
</head>
<body>
<input name="box1" type="text" /><br />
<input name="box2" type="text" /><br />
<input name="box3" type="text" />
</body>
推荐答案
要做的一些更改:
var a = parseInt($('input[name="box1"]').val(), 10);
var b = parseInt($(this).val(), 10);
var c = 15; // really no need to try to build a dom element to get an int
当心,永远不要在未指定 parseInt 的情况下使用基数(parseInt("09") is 0...
).
Beware never never use parseInt without specifying the radix (parseInt("09") is 0...
).
代码中的另一个问题是您尝试在dom准备就绪之前构建jquery集合.使用这个:
Another problem in your code is that you try to build your jquery collection before the dom is ready. Use this :
<script>
$(function(){
$('input[name="box2"]').keyup(function() {
var a = $('input[name="box1"]').val();
var b = $(this).val();
var c = $(15).val();
$('input[name="box3"]').val(a * b * c);
});
});
</script>
请注意,这也是最佳做法,尤其是在使用jQuery时,在主体末尾添加一个script元素以将所有不在单独文件中的javascript保留下来是很容易的.
Note that it's also best practice, especially when using jQuery which makes it easy, to have a script element at the end of the body to keep all the javascript that isn't in separate files.
这篇关于与jquery相乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!