Cli*_*ote 243 javascript jquery jquery-events
Jquery中是否有任何事件仅在用户点击文本框中的enter按钮时触发?或者任何可以添加的插件都包含此内容?如果没有,我将如何编写一个快速插件来执行此操作?
Jis*_*A P 433
您可以连接自己的自定义事件
$('textarea').bind("enterKey",function(e){
//do stuff here
});
$('textarea').keyup(function(e){
if(e.keyCode == 13)
{
$(this).trigger("enterKey");
}
});
Run Code Online (Sandbox Code Playgroud)
Eti*_*uis 94
$('#textbox').on('keypress', function (e) {
if(e.which === 13){
//Disable textbox to prevent multiple submit
$(this).attr("disabled", "disabled");
//Do Stuff, submit, etc..
//Enable the textbox again if needed.
$(this).removeAttr("disabled");
}
});
Run Code Online (Sandbox Code Playgroud)
Nea*_*eal 39
这是一个插件给你:(小提琴:http://jsfiddle.net/maniator/CjrJ7/)
$.fn.pressEnter = function(fn) {
return this.each(function() {
$(this).bind('enterPress', fn);
$(this).keyup(function(e){
if(e.keyCode == 13)
{
$(this).trigger("enterPress");
}
})
});
};
//use it:
$('textarea').pressEnter(function(){alert('here')})
Run Code Online (Sandbox Code Playgroud)
jzi*_*lla 17
这是一个jquery插件
(function($) {
$.fn.onEnter = function(func) {
this.bind('keypress', function(e) {
if (e.keyCode == 13) func.apply(this, [e]);
});
return this;
};
})(jQuery);
Run Code Online (Sandbox Code Playgroud)
使用它,包括代码并将其设置如下:
$( function () {
console.log($("input"));
$("input").onEnter( function() {
$(this).val("Enter key pressed");
});
});
Run Code Online (Sandbox Code Playgroud)
这里的jsfiddle http://jsfiddle.net/VrwgP/30/
应该注意的是,live()自jQuery 以来,jQuery 中的使用已被弃用1.7,并已在jQuery中删除1.9.相反,on()建议使用.
我强烈建议使用以下绑定方法,因为它解决了以下潜在挑战:
document.body第二个参数并将其作为第二个参数传递on(),可以在DOM中附加,分离,添加或删除元素,而无需处理重新绑定或双重绑定事件.这是因为事件是附加到document.body而不是$selector直接附加,这意味着$selector可以添加,删除和再次添加,并且永远不会加载绑定到它的事件.off()之前调用on(),此脚本可以位于页面主体内,也可以位于AJAX调用的主体内,而不必担心意外双重绑定事件.$(function() {...}),该脚本可以再次由页面主体加载,也可以在AJAX调用的主体内加载.$(document).ready()不会因为AJAX请求而被解雇$(function() {...}).这是一个例子:
<!DOCTYPE html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var $selector = $('textarea');
// Prevent double-binding
// (only a potential issue if script is loaded through AJAX)
$(document.body).off('keyup', $selector);
// Bind to keyup events on the $selector.
$(document.body).on('keyup', $selector, function(event) {
if(event.keyCode == 13) { // 13 = Enter Key
alert('enter key pressed.');
}
});
});
</script>
</head>
<body>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
如果您的输入是search,您也可以使用on 'search'事件。例子
<input type="search" placeholder="Search" id="searchTextBox">
Run Code Online (Sandbox Code Playgroud)
.
$("#searchPostTextBox").on('search', function () {
alert("search value: "+$(this).val());
});
Run Code Online (Sandbox Code Playgroud)
小智 5
//简短的解决方案
$(document).ready(function(){
$('#TextboxId').keydown(function(event){
if (event.which == 13){
//body or action to be performed
}
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
303560 次 |
| 最近记录: |