开发者

jQuery: How can I get around using an if statement to get rid of "undefined" errors

When using third-party plugins, I typically initialize them in my main application.js file.

Example:

$('.scroll').jScrollPane();

The problem is if a page loads that doesn't have the scroll class, then I get:

TypeError: Result of expression '$('.scroll').jScrollPane' [undefined] is not a function.

So to get around this, I wrap it in:

if ($(".scroll").length){
    $('.scroll').jScrollPane();
}

That remedies the problem but just seems like a hack.

Is there a "c开发者_开发知识库orrect" way to solve this?


If you're getting:

ScrollPane' [undefined] is not a function.

...it wouldn't be because the page doesn't have a .scroll element.

That sort of error occurs when the plugin (or jQuery itself) isn't loaded.

If you're reusing some code on several pages, some of which don't have that plugin, do this instead:

if ( $.fn.jScrollPane ){
    $('.scroll').jScrollPane();
}


you can use try/catch blocks...

try
  {
    $('.scroll').jScrollPane();
  }
catch(err)
  {
  //Handle or ignore errors here
  }


Uhh ... no; jQuery doesn't work like that. A call to $("any selector") will always give you back a ready-to-use (but empty) jQuery object. I don't think that's really your problem. Can you describe more about what your page is doing?


if ($('.scroll').jScrollPane()){
    $('.scroll').jScrollPane();
}

this error is prob just because an addon failed loading


As a couple others have said, that error is the jScroll's error. If it's because an element doesnt exist jQuery will return an empty array.

Its because the plugin isn't loaded. jScroll is the plugin to change the scrollbars, correct? I've had numerous issues with it. I suggest wrapping it in a

$(window).load(function(){
    //Call it here
})

This fixed all the issues i had with it.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜