开发者

How to make javascript/jquery code error proof?

If jQuery is included in <head> and in <head> if we have some another jQuery code and that code has an id which is a id of an HTML element, so if 开发者_如何学GojQuery library and jquery code in <head> is added globally

And if any page doesn't have that html element which is used by jQuery code then browser gives JavaScript error.

Can I make jQuery/JavaScript code like, if jQuery finds an HTML element with id in <body> then it should work fine.

If another page doesn't have that HTML element with id then I know jQuery will not work.

But what I want:

An error should not be thrown if a page doesn't have an HTML element with the given id.


A lot of jQuery code works like this already, as it is set-based, and you can do operations on sets of 0 elements. I.e. these will always work, regardless of whether or not the selector matches any elements:

$('#myButton').click(function() { ... });
$('#somethingElse').hide();

In some cases you really do need a reference to at least one element, however, for the rest of the script to work. In these cases, you have to manually check that the element exists:

if($('#myElement').length == 0) return false; // or similar...


if($('#myElement').length != 0){
  my special js magic thing;
}else{
  return false;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜