开发者

Use of "setTimeout()" in my jQuery Expression

开发者 https://www.devze.com 2022-12-24 23:07 出处:网络
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

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

精彩评论

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

关注公众号