jQuery-查找元素是否在变量中 [英] jquery - finding if element is in variable
本文介绍了jQuery-查找元素是否在变量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
im试图找出如何查看AJAX请求是否返回了错误.
测试请求始终返回<p id="error">test</p>
im trying to find out how to see if an error is returned from an AJAX request.
for testing the request always returns <p id="error">test</p>
我认为您可以这样做:
//html is the var which contains the result
var DOM = $(html);
if( $('#error', DOM ).length != 0 ) {
alert(html);
}
但是这不起作用.任何人都可以照亮问题所在吗?
but this does not work. Can anyone shine a light on whats going wrong?
推荐答案
如果您的HTML没有包裹在某些东西中(例如div
),则需要包裹它.
If your HTML isn't wrapped in something (like a div
) then it needs to be.
var html = '<div></div><p id="error">ERROR!</p><span>other stuff</span>';
var DOM= $('<div>' + html + '</div>');
if( $('#error', DOM).length != 0 ) {
alert(html);
}
示例: http://jsfiddle.net/jonathon/exqTD/
(我认为wrap
在这里会有所帮助,但没有帮助.如果有人知道为什么,请指出来).
(I thought wrap
would help here but it doesn't. If anyone knows why then point it out).
或者,选择器上下文是使用查找来实现的,因此您可以这样做:
Alternatively, the selector context is implemented using find, so you could just do:
if( DOM.find('#error').length != 0 ) {
alert(html);
}
这篇关于jQuery-查找元素是否在变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文