态势描述
我的HTML加载了一个具有属性valid = "default"的可变数量的元素。
当用户为每个元素输入一个值时,我使用AJAX验证标记,并相应地将valid设置为true或false。
当按下submit按钮时,我收集valid属性值。
问题
jQuery只返回valid的初始值。有没有办法获得valid的更新值?
我使用的代码:
var tags = ($('.tag').map(function () { return $(this).attr('valid') })).get();
返回["default", "default"],即使在更新了值并应该显示["true", "false"]之后
我对JavaScript、jQuery和AJAX都很陌生。所以,如果有更好的方法,请让我知道你的想法。
发布于 2015-03-12 17:07:41
$('#' + field + 'cell')选择td元素,这是具有valid属性的input的父元素,而不是input元素本身,从而导致
.attr("valid", "false")应用于父td元素,而不是子input元素。
尝试删除DOM事件属性,将选择器更改为
$('#' + field + 'cell')
.attr("style", 'border:3px solid #FF0000')
.find("[id="+field+"]").attr("valid", "false")$(function() {
function validate(field, query) {
$.ajax({
type: "POST",
url: "/echo/json/",
data: {json:JSON.stringify(query)}
})
.done(function(response) {
console.log(field, response === "false", response === "true")
//response = response.replace(/[[\]]/g,'');
if(response === 'false') {
$('#' + field + 'cell')
.attr("style", 'border:3px solid #FF0000')
.find("[id="+field+"]").attr("valid", "false")
}
else {
$('#' + field + 'cell')
.attr("style", 'border: none')
.find("[id=" + field + "]")
.attr("valid", "true")
}
})
.fail(function() {
$('#response').html('error');
})
.always(checkForm) // added to verify `checkForm` at each `$.ajax` call
}
function checkForm(variable) {
var tags = $.map($(".tag"), function (el) { return $(el).attr('valid') });
console.log(tags);
}
$("#submitButton").on("click", function(e) {
checkForm()
});
$("[id^=tag]").on("blur", function(e) {
validate(e.target.id, e.target.value)
});
});jsfiddle http://jsfiddle.net/mL8ttwc0/2/
https://stackoverflow.com/questions/29013880
复制相似问题