問題描述
Jquery 響應 find() 失敗? (Jquery respond to find() fail?)
I found this code that let´s me traverse through some xml elements:
$(somexml).find('company[id="'+id+'"] customers customer').each(function()
{
var $tmp = $(this);
alert($tmp.attr('customerid'));
});
seems to work pretty good. But since i´m novice at Javascript/Jquery i have some questions:
How can i respond to when the find() failed...no matches?
Why the '$' before tmp? Why not just var tmp = $(this);
‑‑‑‑‑
參考解法
方法 1:
1: each
returns the object it's been called on, that is $(x).each
returns $(x)
. So, assign the result of each to a variable and check its length:
var obj = $(somexml).find(whatever).each(function() {
...
});
if(!obj.length)
nothing has been found...
2: $tmp
instead of just tmp
is a "hungarian" convention to denote jQuery objects. You are not required to use it.
方法 2:
How can i respond to when the find() failed...no matches?
Assign the result to some variable
result = $(somexml).find('company[id="'+id+'"] customers customer');
if(result.length > 0)
{
result.each(function()
{
var $tmp = $(this);
alert($tmp.attr('customerid'));
});
}
else
{
alert("No results");
}
Why the '$' before tmp? Why not just var tmp = $(this);
You do not need to use $ before tmp. using $
var tmp = $(this);