jQuery - function runs fine when fired on div click, but not on page load

后端 未结 5 917
[愿得一人]
[愿得一人] 2021-01-25 17:49

I have the following function that I want to run on page load and re-run when you click div#trigger. When you click div#trigger everything is fine. However on page load the code

相关标签:
5条回答
  • 2021-01-25 18:13

    Your function need to be called in document.ready call

    $(document).ready(function() {
       textIndentFunc();
    });
    
    0 讨论(0)
  • 2021-01-25 18:26

    Wrap the function call in a document.ready handler like this...

    $(function() {
        textIndentFunc();
    });
    

    That makes sure that the DOM is loaded before trying to do anything to manipulate it, otherwise you'll get different results at different times, depending on what's loaded and what's not.

    0 讨论(0)
  • 2021-01-25 18:32

    Try as below

      $(document).ready(function () {
    $('#trigger').click(function(){
        textIndentFunc();
        alert('fire');
     });
    });
    
    function textIndentFunc () {
    
         textString = $('#from-1 :selected').text();
    
         $('#hidden').text(textString);
    
         textWidth = $('#hidden').width();
    
         inputWidth = $('#from-1 select').width();
    
         indentMy = (inputWidth / 2) - (textWidth / 2);
    
        $('#from-1').css('text-indent',indentMy);
    
    }
    textIndentFunc();
    <div id="trigger">Hai</div>

    0 讨论(0)
  • 2021-01-25 18:33

    If you already are calling textIndendFunc in $(document).ready and is still not getting what you're expecting, try moving textIndentFunc to $(window).load.

    0 讨论(0)
  • 2021-01-25 18:34

    Do you have another function that also runs on page load? Because if this is the case maybe the 2 functions have a conflict...

    0 讨论(0)
提交回复
热议问题