[英]How can i make sure an element was appended and exists after ajax request is succesfull?
如果我使用了以下内容,则假设我从服务器返回的数据是html元素,例如<span id='hiMark'> text </span>
:
...,
success: function(res){
$(res).appendTo('body');
$('#hiMark').css({ … })
}
如果使用此方法,在附加元素上使用方法是否安全,我知道我可以使用.length
和计时器来检查元素是否存在,但是,在这种情况下我是否必须进行检查?
如果服务器端一切正常, css({})
方法是否仅在附加元素之后执行? 还是我需要首先检查它是否存在?
您很安全,无需检查该元素是否存在。
假设res
字符串包含ID为hiMark
的元素,则在success
运行时将立即将其追加到正文中,并且代码将按预期运行。
如果res
不包含这样的元素,任何jQuery方法上调用了ID会静静地什么也不做。
您应该使用以下类似的内容检查响应:
if(response != null && response!= undefined){
//append my stuff
}
要么:
//if your response is a string
if (response != "" )
// if your response is a json object
if(isEmpty(response)) {
// response is empty (Would return true in this example)
} else {
// response is NOT empty
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.