how to try error in jquery?
$(document).ready(function(){
setTimeout(function() {
window.location.href = $(".user a")[0].href;
}, 2000);
});
i put the above jquery code in a js file.which invoked by the site's header template.but in some pages(there is no .user a
) shows an error "0.href is null or not开发者_运维技巧 an object
on IE status bar. how to prevent the error shows.
Check whwther there are any elements on the page which match the selector .user a
, before trying to read from the first one:
$(document).ready(function(){
setTimeout(function() {
if($(".user a").length)
{
window.location.href = $(".user a")[0].href;
}
}, 2000);
});
As mentioned elsewhere, it might be a good idea to change that line also to:
window.location.href = $(".user a").eq(0).attr("href");
$(document).ready(function(){
setTimeout(function() {
if ($(".user a").length > 0)
window.location.href = $(".user a")[0].href;
}, 2000);
});
$(document).ready(function(){
setTimeout(function() {
try {
window.location.href = $(".user a")[0].href;
} catch (e) {
alert('error so no redirect');
}
}, 2000);
});
http://jsfiddle.net/
as pointer out by @Jamiec, you may do $(".user a").length
and check that element exists or not. I have suggested this way (tray catch), as you questions title says so.
you need to use jQuery attributes to prevent cross browser differences
$(document).ready(function(){
setTimeout(function() {
window.location.href = $(".user a").eq(0).attr('href');
}, 2000);
});
精彩评论