jQuery Jquery数学加法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6770389/
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
Jquery math addition
提问by Clay Smith
I'm trying to add through a jquery event and I'm getting NaN. What am I missing?
我正在尝试通过 jquery 事件添加,但结果为 NaN。我错过了什么?
<input type="hidden" id="skillcount" name="skillcount" value="3" onchange="valueadd(this)"/>
function valueadd(ok){
var value=parseFloat($(this).val())+1;
}
采纳答案by Dennis
The code should be:
代码应该是:
function valueadd(ok){
// "this" inside here refers to the window
var value=parseFloat(ok.value)+1;
}
The inline onchange is actually an anonymous function:
内联 onchange 实际上是一个匿名函数:
function() {
//"this" inside here refers to the element
valueadd(this);
}
So "this" is an argument that gets called "ok" in the valueadd scope. As the others have stated, though, you probably want to use jquery's bind so "this" inside of valueadd will point to the element.
所以“this”是一个在valueadd范围内被称为“ok”的参数。但是,正如其他人所说,您可能希望使用 jquery 的绑定,因此 valueadd 中的“this”将指向该元素。
回答by alex
this
is a reserved word in JavaScript, so you can't use it in the function argument signature.
this
是 JavaScript 中的保留字,因此您不能在函数参数签名中使用它。
I'd probably change that code to...
我可能会将该代码更改为...
$('#skillcount').change(function() {
var value = parseFloat($(this).val()) + 1;
});
...and drop the inline event handler.
...并删除内联事件处理程序。
To check if parseFloat()
returns NaN
, use isNaN()
.
要检查是否parseFloat()
返回NaN
,请使用isNaN()
.
回答by brenjt
You should be able to do it simply like so:
你应该能够像这样简单地做到这一点:
<input type="hidden" id="skillcount" name="skillcount" value="3" onchange="valueadd()"/>
function valueadd()
{
var value=parseFloat(this.value)+1;
}
回答by JAAulde
- Assign your behavior with jQuery since you have it available and are using it anyway. Don't use inline event handlers
- A function bound by jQuery is executed in scope of the element on which the event occurred. Which means
this
is the element. this
cannot be used as a param name or anything other than to access the object in scope.
- 使用 jQuery 分配您的行为,因为您可以使用它并且无论如何都在使用它。不要使用内联事件处理程序
- jQuery 绑定的函数在发生事件的元素范围内执行。这意味着
this
是元素。 this
不能用作参数名称或除访问范围内的对象以外的任何内容。
Use:
用:
<input type="hidden" id="skillcount" name="skillcount" value="3" />
<script type="text/javascript">
$( '#skillcount' ).bind( 'change', function()
{
var value = parseFloat( $( this ).val() ) + 1;
} );
</script>