开发者

Use of "setTimeout()" in my jQuery Expression

I'm trying to add the JavaScript function setTimeout() to my jQuery expression. Without the setTimeout() my function loads a partial view with updated information when I enter text into my textbox. But, it loads the information with every keystroke. My logic is that if I can put in a timer then when the user stops typing, a second later the data is updated.

As you can see I tried to put a setTimeout开发者_C百科() in but it doesn't seem to be working.

$(function() {
    $('#DocId').live('keyup', function() {
        setTimeout(var styleValue = $(this).val();
        $('#tableContent').load(
        '/CurReport/TableResults', 
        { style: $(this).val()}), 1000);

    }),
});

Thank you,

Aaron


You can use .data() and put in a delay timer that resets every keystroke like this:

$('#DocId').live('keyup', function() {
  clearTimeout($.data(this, 'timer'));
  var val = $(this).val();
  var wait = setTimeout(function() {
    $('#tableContent').load('/CurReport/TableResults', { style: val });
  }, 1000);
  $(this).data('timer', wait);
});

This sets a timeout of 1 second every keystroke on the element that it's typed it (can have any number of these going at once). Each keystroke clears the previous timer and sets a new one, so only after 1 complete second of not typing will the function fire.

Note: don't remove the var val = $(this).val(); portion, you need the variable because this is a different context when the function actually executes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜