我有(部分)PHP循环生成的表单HTML:
<input type="text" class="store">
<input type="text" class="store">
<input type="text" class="store">
<input type="text" class="store">
输入进入db表:
store
-------
cityID
cityname
store
如果输入的商店已经在其他城市,我有一个提醒我的JavaScript:
$(document).ready(function() {
$('.store').on('change', function() {
var storeValue = $('.store').val();
$.post('stores.php', {'word': storeValue}, function(data) {
var verifStore = '';
var json = $.parseJSON(data);
$.each(json, function(k, v) {
verifStore += '[' + v.cityID + '] ' + v.cityName + '\n';
});
alert('Already in the following cities: ' + '\n' + verifStore);
});
});
});
问题是JavaScript被.class
触发,我的表单中有更多.class
个输入,所以(当然)它无法正常工作。我该如何修改我的JavaScript代码?也许在JavaScript中有一种方法可以单独考虑每个.class
字段...类似于.each
或.foreach
......?
答案 0 :(得分:1)
假设您被要求为城市设置4个不同的值,并且它们不应该出现在数据库中。我会创建一个名为error
的类:
.error {border: 1px solid #f00; background: #f99;}
现在,我将使用input
:
$.each
$(".store").each(function () {
$this = $(this);
$this.removeClass("error");
$.post('stores.php', {'word': $this.val()}, function (data) {
if ( /* Your condition if the word is present. */ )
alert("Already there!");
});
});
请注意,此代码将向服务器发送尽可能多的输入。所以小心处理。
答案 1 :(得分:0)
如果您只提出一个请求,则可以优化您的功能。
var values = $(".store").map(function(){
return this.value;
}); // values is an array
$this.removeClass("error");
// stores.php should be ready to receive an array of values
$.post('stores.php', {'word': JSON.stringify(values)}, function (data) {
var verifStore = '';
var json = $.parseJSON(data);
$.each(json, function(k, v){
verifStore += '[' + v.cityID + '] ' + v.cityName + '\n';
});
if(varifStore)
alert('Already in the following cities: ' + '\n' + verifStore);
});
答案 2 :(得分:0)
解决方案(至少对我而言......)
在阅读完所有答案和建议后,我能够使用此代码。希望它对其他人有所帮助:))
{{1}}
});