我有两个文本类型的输入,当用户开始写东西时,我写了一个 onkeyup 函数,我将数据发送到另一个名为“jsonpage.html”的页面。 但是我的代码的成功部分不起作用。 我认为它找不到 divs 的地址。但起初它可以找到它。我不知道为什么它在成功部分不起作用? 如果你省略部分 "$(this).closest(".main").find"成功它工作。但是在我添加这些行之后它没有。
这是我的代码片段:
$('.country').each(function() {
$(this).on('keyup', function(e) {
var element = $(this).val().length;
if (e.which !== 0 &&
!e.ctrlKey && !e.metaKey && !e.altKey
) {
if (element > 2) {
$(this).closest(".main").find(".mini-loading").css("display", "block")
var val = $(this).val()
val = val.substr(0, 1).toUpperCase() + val.substr(1).toLowerCase();
$(this).val(val)
$.ajax({
url: "jsonpage.html",
type: "get",
contentType: 'application/json; charset=utf-8',
data: {
key: $(this).val()
},
success: function(result) {
$(this).closest(".main").find(".mini-loading").css("display", "none")
$(this).closest(".main").find(".co").empty().html(result)
}
})
}
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="main">
<div class="city1">
<input type="text" value="" class="country" placeholder="First City" />
<input value="" type="hidden" />
<div class="mini-loading" style="display: none; ">
LOADING
</div>
<div class="co"></div>
</div>
</div>
<div class="main">
<div class="city2">
<br/>
<input type="text" value="" class="country" placeholder="Second City" />
<input value="" type="hidden" />
<div class="mini-loading" style="display: none; ">
LOADING
</div>
<div class="co"></div>
</div>
</div>
最佳答案
问题可能是由于成功回调函数中的 this
的范围不再指向您的输入,而是指向 ajax 调用。
尝试像这样存储你的值(value):
$(this).on('keyup', function(e) {
// Store the initial value of this ---------------------------------
var _this = this;
var element = $(this).val().length;
if (e.which !== 0 &&
!e.ctrlKey && !e.metaKey && !e.altKey
) {
if (element > 2) {
$(this).closest(".main").find(".mini-loading").css("display", "block")
var val = $(this).val()
val = val.substr(0, 1).toUpperCase() + val.substr(1).toLowerCase();
$(this).val(val)
$.ajax({
url: "jsonpage.html",
type: "get",
contentType: 'application/json; charset=utf-8',
data: {
key: $(this).val()
},
success: function(result) {
// And use it here at least ----------------------
$(_this).closest(".main").find(".mini-loading").css("display", "none")
$(_this).closest(".main").find(".co").empty().html(result)
}
})
}
}
})
您还可以使用 $(e.target)
(事件目标元素)代替 this
来取回您的输入元素
最后,您还可以使用 jquery 上下文选项。参见 How to pass context in jquery ajax success callback function
关于javascript - 功能的成功部分不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48644913/