duancan1732 2018-02-08 06:48
浏览 57

在HTML文档中包括JS和CSS?

I'm running an http server instance with Go and I would like to return the HTML doc to a client, but the JS and the CSS files are not working. How do I make the JS and CSS get sent along with the HTML if they are in different files?

Go Code

package main
import (
"fmt"
"io/ioutil"
"net/http"
)

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}

func handler(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "text/html")
    file, _ := ioutil.ReadFile("webpage.html")
    s := string(file)
    fmt.Fprintf(w, s)
}

webpage.html

<!DOCTYPE HTML>
<html lang="en">
    <head>
        <meta charset="UTF-8"/>
        <title>html file</title>
        <link rel="stylesheet" type"text/css" href="styles.css"/>
    </head>
    <body>
        <h1>Click to change color</h1>
        <script src="changeColor.js"></script>
    </body>
</html>

And changeColor.js

function init(){
var h1tags = document.getElementsByTagName("h1");
h1tags[0].onclick = changeColor;
}

function changeColor(){
    this.style.color = '#000000';
}
onload = init;

CSS is in a file called styles.css in the same directory as the HTML doc.

  • 写回答

3条回答 默认 最新

  • 普通网友 2018-02-08 08:00
    关注

    In your Go code, you need to do it like this :

    func main() {
    http.HandleFunc("/", handler)
    
    http.HandleFunc("/changeColor.js", func(w http.ResponseWriter, r *http.Request) {
        http.ServeFile(w, r, "changeColor.js")
    })
    
    http.HandleFunc("/styles.css", func(w http.ResponseWriter, r *http.Request) {
        http.ServeFile(w, r, "styles.css")
    })
    
    http.ListenAndServe(":8080", nil)
    }
    

    Because go server for this line

        <link rel="stylesheet" type"text/css" href="styles.css"/>
    

    looks this pattern "/styles.css" and your server does not handle this request.

    And you can replace this code

    http.HandleFunc("/", handler)
    

    whit this

    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        http.ServeFile(w, r, "webpage.html")
    })
    
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!