为变量指定一个唯一的名称 JavaScript/jQuery

giving a variable a unique name javascript/jquery

本文关键字:唯一 JavaScript jQuery 一个 变量      更新时间:2023-09-26

我正在尝试设置一个函数,以便在文本区域中的键控事件后运行 1.5 秒。但是,如果在同一区域发生另一个 keyup 事件,我想再次将时间延长到 1.5 秒,或者取消旧函数并使用新功能更新它。

让事情变得更加有趣 xD有多个文本区域,每个文本区域都有自己唯一的 ID。我希望它仅在 keyup 事件来自同一文本区域时才取消。

以下是我一直在尝试做的一个例子。

$(document).on("keyup",".edit_main textarea",function(e){
  location_val = //textareas unique ID 
  curval = $(this).val();
  blue = "blue";
  UNIQUE_VARIABLE = blue+location_val;
  clearTimeout(UNIQUE_VARIABLE);
  UNIQUE_VARIABLE = setTimeout(function(){
    // do cool stuff
  }, 1500);
});

这样它只会清除一次,但它会被覆盖。所以我尝试使用数组,但我不确定您是否可以使用它存储超时。

如果我的问题太模糊,请说出来,我会尽量更详细。

对于超时本身,你不需要唯一的id,你可以使用jQuery的.data()功能为每个元素设置唯一的超时。

  $(document).on("keyup",".edit_main textarea",function(e) {
    var textArea = $(this);
    var curval = textArea.val();
    var blue = "blue";
    clearTimeout( textArea.data().keyupTimeout );
    textArea.data().keyupTimeout = setTimeout(function(){
      // do cool stuff
      textArea.val('the cool result');
    }, 1500);
  });

这比它需要的要复杂得多。您似乎在范围方面遇到了问题。请查看下面记录的代码解决方案。另外,你也可以看看jsFiddle。希望这是有帮助的!

//This needs to be declared OUTSIDE the function.
var unique;
//No need to use $(document), target your textareas directly.
$('.edit_main textarea').on('keyup', function(e){
    //$(this) doesn't work here. Use e (an argument for the event). e.target.id gets the textarea's id.
    var location_val = e.target.id;
    //e.target.id returns just the id. 
    //We need to prepend the CSS selector for jQuery to find the element.
    var curval = $('#'+location_val).val();
    //I don't see the point of blue = 'blue', so I omitted it.
    //Clear the timeout first if any.
    clearTimeout(unique);
    //Set a new one.
    unique = setTimeout(function(){ 
        //Do something cool. Like telling you what's in the textarea.
        alert(curval); 
    }, 1500);   
});