以下是我的HTML代码:
<textarea id="uno-1" name="1"></textarea>
<textarea id="uno-2" name="2"></textarea>这是我的JS代码:
$("[id^=uno]").keyup(function() {
clearTimeout(typingTimer);
if ($("[id^=uno]").val) {
typingTimer = setTimeout(function() {
$.get("/someUrl", {
text: $("[id^=uno]").val(),
id: $("[id^=uno]").attr('name')
});
}, 1000);
}
});重点是,文本是自动保存的,发送到获取Url后,立即键入它。但是,问题是,即使我在第二个文本区域中键入文本,它也总是只捕获第一个文本区域。我需要分别发送GET属性。有办法做到这一点吗?
发布于 2016-05-26 18:56:22
因为您总是引用所有输入,而不是只使用当前输入。
$("[id^=uno]").keyup(function() {
clearTimeout(typingTimer);
var input = $(this); //reference the current textarea
if (input.val().length) { //not sure what your check was, but it was strange
typingTimer = setTimeout(function() {
$.get("/someUrl", {
text: input.val(), //use the variable we set about
id: input.attr('name')
});
}, 1000);
}
});发布于 2016-05-26 18:57:02
首先,使用类对元素进行分组:
<textarea id="uno-1" class="uno" name="1"></textarea>
<textarea id="uno-2" class="uno" name="2"></textarea>然后,您可以使用该类以及事件处理程序中的this关键字来引用引发事件的元素。
var typingTimer;
$(".uno").keyup(function() {
clearTimeout(typingTimer);
if (this.value) {
typingTimer = setTimeout(function() {
$.get("/someUrl", {
text: this.value,
id: this.name
});
}, 1000);
}
});发布于 2016-05-26 18:55:38
您的问题是使用$("[id^=uno]").val()和$("[id^=uno]").attr('name')。
$("[id^=uno]")选择这两个字段。
然后,.val()从第一个字段返回值。
若要修复此问题,请使用回调中的$(this)。
setTimeout还将创建一个新的函数作用域,因此请确保使用以下内容从keyup(function () {捕获this的值:
self = this;
//or
$this = $(this);https://stackoverflow.com/questions/37468895
复制相似问题