2010-03-08 76 views
1

我有一個文本框,並希望觸發一個事件,無論是通過按鍵,從剪貼板粘貼,還是其他任何可能的更新。事件的文本框更新

綁定到keyup事件是否足夠或有沒有更好的方法?

回答

1

我做同樣的事情在同樣的效果與此代碼的文本字段:

$(document).ready(function(){ 

    $('#link').keyup(function(event){  

     if($(this).val().length > 30 && this.value != this.lastValue){ 
      if (this.timer) clearTimeout(this.timer); 

      if(!$('#ajax-aguarde').length) 
      { 
       $('<p id="ajax-aguarde"></p>').appendTo($('#link-element')); 
      } 
      $('#ajax-aguarde').html('Wait, loading...'); 

      if($('#posts').length){ 
       $('#posts').remove(); 
       $('#p-ultimos').remove(); 
      } 

      str = this.value; 
      url = $('#ajaxurl').val(); 

      this.timer = setTimeout(function() { 
       $.post(
       url, 
       { link: str, format: 'json' }, 
       function(data){ 

        if(data.error == 1){ 
         $('#ajax-aguarde').html('Error...'); 
        } else { 
         $('#ajax-aguarde').remove(); 
        } 

        if(data.titulo.length){ 
         $('#titulo').val(data.titulo); 
        } 
        if(data.descricao.length){ 
         $('#descricao').val(data.descricao); 
        } 

        $('<p id="p-ultimos">Last posts:</p>').appendTo($('#link-element')); 
        $('<ul id="posts"></ul>').appendTo($('#link-element')); 

        $.each(data.posts, function(index, post) { 
         $('<li id="post' + index + '"></li>').appendTo($('#posts')); 
         $('#post' + index).html(post.title); 
        }); 


       }, 
       "json" 
       ); 
      },1000); 

      this.lastValue = this.value; 
     } 

    }); 

    setTimeout(function() { $('#link').keyup(); },500); 
}); 

我已經setTimeout的,以確保一些事件沒有被觸發

0

我認爲這取決於你想如何經常聽我認爲ketup會做,但平變化可能不太intenseive,讓你它只是取決於你做什麼

2

可以綁定多個事件是這樣的:

$('#textbox').bind('keyup change blur', function() { 
    // stuff to do when any of these events fire 
}); 

聽起來好像change()一個人應該爲你工作,但。

Here is the API doc

+0

更改是我的第一個想法,但我發現它不會在文本更改時觸發。關鍵事件的確如此。 – hoju 2010-03-09 00:39:13