简体   繁体   English

在单独的HTML文件中使用Javascript函数

[英]Using Javascript functions in a separate HTML file

I know it might seem like a dumb question but even with all the examples i have looked through i can not get it too work. 我知道这似乎是一个愚蠢的问题,但即使通过我浏览过的所有示例,我也无法解决它。 I have the following code in my Javascript file 我的Javascript文件中有以下代码

server.js server.js

  // Google Maps Locaton 
  googleMapsClient.geocode({
    address: city
  }, function(err, response) {
    if (!err) {
      basicLocation = response.json.results[0].formatted_address;
      console.log(basicLocation);
    }
  });

});

function getBasicLocation() {   // Able to grab location from index.ejs file 
  return basicLocation;
}

in my HTML im trying to update text as the location changes. 在我的HTML中,我尝试随着位置的变化而更新文本。 My html code looks like this 我的html代码看起来像这样

index.ejs index.ejs

<script src="../server.js">
    </script>
      <h3>
        <script> getBasicLocation() </script> Location
      </h3>

The way my files are set up in the directory is like 我的文件在目录中的设置方式就像

- app 
   - views 
     - index.ejs
   - server.js

How do i get the getBasicLocation() to talk to my index.ejs file so that it updates the text? 如何获取getBasicLocation()与index.ejs文件对话,以便更新文本?

Below steps should work - 以下步骤应该可以-

  1. Import server.js - You are doing this 导入server.js-您正在执行此操作
  2. create HTML node where you want location eg div id="location" 在想要的位置创建HTML节点,例如div id =“ location”
  3. create script tag with below content 使用以下内容创建脚本标签

      let lc = getBasicLocation(); document.getElementById("location").innerHTML = lc; 

JQuery can further simplify your node selection code jQuery可以进一步简化您的节点选择代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM