document.getElementById not working on jquery load

[亡魂溺海] 提交于 2021-01-28 09:53:45

问题


I've loaded an html file with jquery load function

in my profile.blade.php

 <script type="text/javascript">
      $(document).ready(function(){
         $("#newJob").load('/company/new-job');
      });
    </script>
   <script src="js/location.js"></script>

in my location.js i am using

document.getElementById('autocomplete') for getting an html element

but this element is in company/new-job file

the problem i got undefined error in document.getElementById('autocomplete') this part

when i directly include the location.js its working fine


回答1:


Try using load's callback function to insert the script you wish:

$(document).ready(function(){
    $("#newJob").load('/company/new-job', null, function(){
        $.getScript('js/location.js');
    });
});



回答2:


You need to include location.js in the html page returning from /company/new-job to get it work.

Or try loading the js like below. (not tested)

$(document).ready(function(){
     $("#newJob").load('/company/new-job',function(data){
     //here you can get the elements from /company/new-job.
       $.getScript('js/location.js').done(function(data, textStatus, jqxhr) {
          //here you can call functions from location.js
       });         
     });
});



回答3:


your script <script src="js/location.js"></script> load before $(document).ready(function() and your element will load after document is ready and .load mehtod.

So here need to do is that have to add your script after your element render. otherwise document.getElementById('autocomplete') cant't find element and generate error.

$(document).ready(function(){ 
$("#newJob").load("/company/new-job", function(responseTxt, statusTxt, xhr){
        if(statusTxt == "success")
           $.getScript('js/location.js');
        if(statusTxt == "error")
            alert("Error: " + xhr.status + ": " + xhr.statusText);
    });
});


来源:https://stackoverflow.com/questions/44449885/document-getelementbyid-not-working-on-jquery-load

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