jQuery keyup = instead of ==
jQuery keyup = instead of ==
我使用jQuery在Javascript中编写了一个函数,它以我想要的方式工作。问题是,我犯了一个错别字,使用了赋值操作符,而不是==或===。由于某些原因,赋值操作符可以工作,而检查相等==则不能。下面的函数可以工作,但看起来不应该。我指的是事件。键入= 'keyup'。知道为什么吗?
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class = "box" id = "box1">
<input class = "ti" id = "t1" type="text" placeholder= "Enter to do" >
</div>
<script>
$( ".ti" ).on( "keydown", function( event ) {
$( "#log" ).html( event.type + ": " + event.which );
if (event.type = 'keyup' && event.which == '13') {
alert('here');
}
});</script>
这是因为event.type = 'keyup'
返回keyup
,而非空字符串在JavaScript中是真值。
编辑:我错过了&&
操作符和它在表达式中的作用,也许是因为我专注于JavaScript中非空字符串的真实性质,这仍然与发生的事情相关。所以这个答案在你的情况下并不完全正确。因为Kay已经发布了一个正确的答案,所以我不会更新这个答案。
在JavaScript中,逻辑AND (&&
)具有比赋值(=
, +=
,…)更高的优先级,即a = b && c
被解析为a = (b && c)
。
所以条件event.type = 'keyup' && event.which == '13'
被解析为event.type = ('keyup' && (event.which == '13'))
。非空字符串在JavaScript中是真实的,所以这个表达式可以简化为event.type = (event.which == '13')
。注意,字符串"keyup"从表达式中消失了。现在,赋值计算为赋值,即event.type
根据event.which
的值被覆盖为true或false,并且这个比较决定if-condition是否为真。
相关文章:
- HighChart : Usage of setData
- Difference between methods of defining JavaScript 'class
- 为什么我在下面的..of循环中得到意外令牌
- Appending the innerhtml of <th>
- Animation cuts off multiple lines of text in <p>
- javascript: functionname() instread of functionname()
- Object.create() instead of prototype
- new instead of Object.create
- CSS3 Transitions instead of jQuery
- JQuery appendTo Div with ID instead of appendTo('body
- jQuery 0 instead of Nan
- indexOf(model.object) instead of indexOf(model) not working
- nextSibling instead of nextElementSibling?
- jQuery keyup = instead of ==
- jQuery fadeIn / fadeOut instead of fadeToggle
- "jQuery(...)" instead of "$(...)"
- Use Observable instead of Promise
- onkeyup instead of on submit
- JavaScript instead of "echo"
- CSS : picture instead of backface-visibility = hidden