我的外部函数从javascript不加载之前的html

My external function from javascript doesnt load before html

本文关键字:html 加载 外部 函数 javascript 我的      更新时间:2023-09-26

我正在使用INTEL XDK和bootstrap主机开发一个移动应用程序。我有Html代码和一些外部js文件与功能运行在它。由于某种原因,JS文件中的函数dosmth()没有在HTML之前加载,所以它没有给我任何结果。(函数应该返回一个字符串数组)。有人能告诉我我的代码有什么问题吗?我错过了什么

包含文件的HTML标题。

      <script src="js/file.js"></script>

这是在我的HTML文件中调用函数的代码。

    <h4>
        <script type="text/javascript">
              document.write(dosmth());
         </script>
    </h4>

js文件中方法的代码。

        function getCities()
          {
            var url = file.api + "name";
             console.log(url);
             $.getJSON(url).done(function(response){
                              if (!response.length) {
                              console.warn("Empty");
              }
                          file.name = response;
                        $('body').trigger('name-data');
                           console.log(response);
                           return (response);
                    }.fail(function(data, status, error){
                       console.error("Something went wrong");
                                  });
                     }

也许这有帮助。

首先,确保HTML标记是可选择的。例如,为这个h4指定一个id。

<h4 id="cities"></h4>

在调用JS函数之前,你还需要等待文档加载完成:

<script type="text/javascript">
     window.onload = function() {
         getCities();
     );
</script>

我们不返回任何东西,而是更新h4

function getCities()
{
    var url = file.api + "name";
    $.getJSON(url).done(function(response){
        if (!response.length) {
            console.warn("Empty");
        }
        // don't know what these two lines are meant to do
        file.name = response;
        $('body').trigger('name-data');
        // update the h4 element
        $('#cities').html(response);
        // the next line was missing a ")" before ".fail"
    }).fail(function(data, status, error){
        console.error("Something went wrong");
    });
}