为变量指定一个唯一的名称 JavaScript/jQuery
giving a variable a unique name javascript/jquery
我正在尝试设置一个函数,以便在文本区域中的键控事件后运行 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);
});
相关文章:
- 当同一浏览器的两个实例浏览时,Javascript页面如何具有唯一的ID
- 获取唯一值并使用javascript计算金额总和
- JavaScript:从对象数组中获取唯一值及其计数
- 创建具有2个唯一数字的Javascript数组
- 在JavaScript中创建全局唯一ID
- JavaScript-用唯一属性标识对象
- 如何为动态创建的元素分配唯一的id-Javascript
- JavaScript会删除页面上的所有唯一图像
- 比较两个数组得到唯一值javascript
- javascript和具有唯一密钥的es6过滤器数组
- 将数组中的重复项转换为唯一项,而不删除Javascript中的任何项
- 如何在javascript中生成唯一的id
- JavaScript:将 URL 字符串转换为唯一标识符
- 在 javascript 或 jquery 中唯一的 3 个或更多数组对
- 创建唯一选项,然后使用 JavaScript 填充多个选择
- Javascript:编写一个函数,接收一个数组,然后返回一个只有唯一数字的数组,只删除数组
- 创建在Javascript和PHP之间使用的唯一代码的最简单方法
- 如何使用Javascript使多列唯一,解析云代码
- 在javascript循环中创建唯一的Id按钮
- 基于一个属性的唯一javascript数组