jQuery Plugins triggerable by Console, but not by function - why that?

送分小仙女□ 提交于 2019-12-12 05:28:43

问题


I have a mysterious JS Problem: I activate different jQuery-Plugins with one function. It's called like this:

<script>
postAjaxCalls();
</script>

Then, the corresponding function looks like this:

function postAjaxCalls() {
    jQuery("[title]").tooltip(); 
    alert("this works great, tooltip not!");
    jQuery("select").selectbox();
} 

When I reload the page, everything works but the tooltip plugin. Now, if I fire the exact same Code into the JS Console, the plugin is activated:

jQuery("[title]").tooltip(); 

Why that? Why does it work when activated via console, but doesn't work when activated via a function?

Cheers!


回答1:


Try your code within $(document).ready(function() { .. }) in short $(function() { .. }) to execute your code after DOM ready.

jQuery(document).ready(function() {

  function postAjaxCalls() {
    jQuery("[title]").tooltip(); 
    alert("this works great, tooltip not!");
    jQuery("select").selectbox();
  } 
  postAjaxCalls();

});

OR in short

jQuery(function() {

  function postAjaxCalls() {
    jQuery("[title]").tooltip(); 
    alert("this works great, tooltip not!");
    jQuery("select").selectbox();
  } 
  postAjaxCalls();

});



回答2:


You are probably calling postAjaxCalls before the DOM is ready. When you call it from the console, the DOM is ready, so it works.

Try this:

$(function(){
    postAjaxCalls();
});


来源:https://stackoverflow.com/questions/11545467/jquery-plugins-triggerable-by-console-but-not-by-function-why-that

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!