如何仅在字段中的第一个keyup上创建keyup()函数

我已经创建了一个代码在这里的keyup()函数

$(document).ready(function() { var scntDiv = $('#add_words'); var wordscount = 1; $(document).keyup(function(e) { var key = (e.keyCode ? e.keyCode : e.which); if (key === 32) { wordscount++; $('.input1').append('

stop touching your keyboard

'); $('
Word ' + wordscount + 'Remove
').appendTo(scntDiv); i++ return false; } }); });
Word 1

哪个工作正常,但每当我按空格键添加新的输入字段。 问题是我无法用空格键入长词(来了很多输入字段)

例如: – 当输入“my hello world”时显示两个输入字段。 实际上我需要一个额外的字段。

我的问题是,是否有任何选项keyup()函数仅在第一次在同一字段中工作

如果你知道,请你帮我

我认为这就是你所要求的

 $(document).ready(function() { var scntDiv = $('#add_words'); var wordscount = 1; $("#add_words").on("keyup","input[type='text']",function(e) { // Set the eventhandler to the inputs var key = (e.keyCode ? e.keyCode : e.which); if (key === 32) { if($(this).attr("data-isused")!="true"){ // Check if THIS textbox have append a new textbox? $(this).attr("data-isused","true"); // Mark that this textbox has append a new one wordscount++; $('.input1').append('

stop touching your keyboard

'); $('
Word ' + wordscount + 'Remove
').appendTo(scntDiv); //i++ Ignore this, couse its not declared return false; } } });

});

JS小提琴: http : //jsfiddle.net/pURVS/

您可以使用一种方法在首次使用后自动取消绑定事件:

 $("#foo").one("keyup", function() { alert("This will be displayed only once."); }); 

你可以使用jQuery .one()

 $('#myinput').one('keyup',function(){ // do something }); 

我不确定你到底想要什么,但试试这个……

使用HTML5 data.*来了解之前使用过该空间的用户。

 $(document).ready(function() { var scntDiv = $('#add_words'); var wordscount = 1; $(document).keyup(function(e) { var key = (e.keyCode ? e.keyCode : e.which); if (key === 32 && $(e.target).data('added')) { // <=== Here $(e.target).data('added', 'added'); // <=== And Here wordscount++; $('.input1').append('

stop touching your keyboard

'); $('
Word ' + wordscount + 'Remove
').appendTo(scntDiv); i++ return false; } }); });

不,但您可以将类添加到目标输入字段并测试它是否已在此处,然后不执行任何操作

你应该使用bind和unbind方法:

http://api.jquery.com/bind/ http://api.jquery.com/unbind/

例如:

 var handler = function() { alert('The quick brown fox jumps over the lazy dog.'); // unbind handler so the function is not executed again $('#foo').unbind('click', handler); }; $('#foo').bind('click', handler); 

在处理程序函数中,如果您不再希望执行它(在第一次按键之后),则调用unbind方法。