Go web开发判断table里元素的大小,并根据数据正负或大小设置不同样式

问题描述:

比如新浪财经美股行情中心,涨跌额和涨跌幅,正数显示红色,负数显示绿色
行情中心
在用Go语言开发时,如何实现这样的效果?

第一种方法:不使用js

Go语言内置了一些进行模板渲染的函数,在官方源码/src/text/template/funcs.go中,专门用于GoWeb模板中的数据判断或比较

type FuncMap map[string]interface{}

var builtins = FuncMap{
	"and":      and,
	"call":     call,
	"html":     HTMLEscaper,
	"index":    index,
	"js":       JSEscaper,
	"len":      length,
	"not":      not,
	"or":       or,
	"print":    fmt.Sprint,
	"printf":   fmt.Sprintf,
	"println":  fmt.Sprintln,
	"urlquery": URLQueryEscaper,

	// Comparisons
	"eq": eq, // ==
	"ge": ge, // >=
	"gt": gt, // >
	"le": le, // <=
	"lt": lt, // <
	"ne": ne, // !=
}

根据字面意思以及注释就知道哪个是干什么的,比如eq就是判断两个元素是否相等,lt就是判断a元素是否小于b元素。
.html文件中的用法是

{{if gt .Percent 0.0}}

即判断.Percent是否大于0,如果Percent是整数,就要写成0,即跟0比较;如果Percent是小数,就要写成0.0,否则就因会类型不一致报错。
接下来用一个完整的例子,看一下到底怎么使用。
建立一个项目,结构如下:

.
├── main.go
├── test
│   └── test.go
└── view
    └── test.html

2 directories, 3 files

也就只有三个文件,不过就把如何注册处理函数,如何启动一个服务器,如何给前端传递数据,以及前端如何渲染数据都概括了。
main.go文件

package main

import (
	"net/http"
	"GoProject/test"
)

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

这里注册了一个处理函数test,做具体的逻辑处理,然后启动服务器,监听8080端口
test.go文件

package test

import (
	"fmt"
	"html/template"
	"net/http"
)

type Data struct {
	Country string
	Percent float64
}

var Datas []*Data

//初始化数据
func init() {
	d1 := &Data{"利比里亚", 4.50}
	d2 := &Data{"布隆迪", 3.90}
	d3 := &Data{"阿富汗", 3.85}
	d4 := &Data{"喀麦隆", 2.00}
	d5 := &Data{"香港", 1.00}
	d6 := &Data{"古巴", -0.01}
	d7 := &Data{"摩尔多瓦", -0.90}
	d8 := &Data{"纽埃", -1.85}
	d9 := &Data{"库克群岛", -2.23}
	Datas = append(Datas, d1, d2, d3, d4, d5, d6, d7, d8, d9)
}

//处理函数:handler func(ResponseWriter, *Request))
func Test(w http.ResponseWriter, r *http.Request) {
	t, err := template.ParseFiles("view/test.html")
	if err != nil {
		fmt.Println(err)
	}
	t.Execute(w, Datas)
}

首先准备一些数据,保存在Datas数组中,然后传递给模板test.html
test.html模板文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>测试</title>
</head>
<body>
<div style="width: 500px;height: 300px;margin-left: 500px;margin-top: 100px;">
    <table style="margin-top: 100px;width: 330px">
        <h2>世界各国人口增长率</h2>
        <thead style="width: 300px">
        <tr style="width: 260px;">
            <th style="">国家</th>
            <th style="">增长率</th>
        </tr>
        </thead>
        <tbody>
        {{range .}}
            <tr style="width: 260px;">
                <td style="color: blue;">{{.Country}}</td>
                {{if gt .Percent 0.0}}
                    <td style="color: red">{{.Percent}}</td>
                {{else}}
                    <td style="color: green">{{.Percent}}</td>
                {{end}}
            </tr>
        {{end}}
        </tbody>
    </table>
</div>
</body>
</html>

这里的{{range .}}表示遍历后端传递过来的数据,.即表示传递过来的所有数据t.Execute(w, Datas),注意要有{{end}}结束遍历。

{{range .}}{{end}}中的{{.Country}}{{.Percent}}就是每一个Data中的两个数据。

这里的{{if gt .Percent 0.0}}就是判断增长率Percent是否大于0,由于Percentfloat64类型,所以要跟0.0比较,否则会导致类型不一致,报错。

{{if gt .Percent 0.0}}
	<td style="color: red">{{.Percent}}</td>
{{else}}
	<td style="color: green">{{.Percent}}</td>
{{end}}

只需一段if语句,即完成了table表格中元素大小的判断,然后大于0的设置红色,小于0的设置绿色。
接下来运行main.go,用浏览器访问http://localhost:8080/,效果如下
世界各国人口增长率

第二种方法:使用js

使用js就稍微麻烦一些,要添加jquery库,代码也会多一些。项目结构如下,需要添加jquery库,并在html模板中引入js文件,然后还要写js代码。

.
├── main.go
├── static
│   ├── jquery-3.3.1.min.js
│   └── jquery.url.js
├── test
│   └── test.go
└── view
    └── test.html

3 directories, 5 files

就是比刚才多了个static文件夹,多了两个js文件。

首先要在main函数中注册静态文件服务

在刚才的main.go文件中增加两行代码,


func main() {
	fs := http.FileServer(http.Dir("static"))
	http.Handle("/static/", http.StripPrefix("/static/", fs))
	http.HandleFunc("/", test.Test)
	http.ListenAndServe(":8080", nil)
}

也就是告诉编译器,静态文件→包括jscssjpeg图片文件在什么地方,这一段代码就是说静态文件在项目的根目录下的static文件夹下。如果没有这一段代码,那么编译器就找不到js文件在哪里,因此html文件中的js代码就不会被执行。

然后在test.html中增加一些代码,具体如下

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>测试</title>
    <script type="text/javascript" src="../static/jquery-3.3.1.min.js"></script>
    <script type="text/javascript" src="../static/jquery.url.js"></script>
    <script>
        function changeColor() {
            $('.percent').each(function (i) {
                var colorStr = '';
                if ($('.percent').eq(i).html() > 0) {
                    colorStr = 'red';
                } else {
                    colorStr = 'green';
                }
                $('.percent').eq(i).css('color', colorStr);
            });
        }
    </script>
</head>
<body onload="changeColor()">
<div style="width: 500px;height: 300px;margin-left: 500px;margin-top: 100px;">
    <table style="margin-top: 100px;width: 330px">
        <h2>世界各国人口增长率</h2>
        <thead style="width: 300px">
        <tr style="width: 260px;">
            <th style="">国家</th>
            <th style="">增长率</th>
        </tr>
        </thead>
        <tbody>
        {{range .}}
            <tr style="width: 260px;">
                <td style="color: blue;">{{.Country}}</td>
                <td class="percent" style="">
                    {{.Percent}}
                </td>
            </tr>
        {{end}}
        </tbody>
    </table>
</div>
</body>
</html>

也就是增加了一个js函数,获取目标元素,并判断目标元素的大小,根据正负设置不同的样式

<script>
        function changeColor() {
            $('.percent').each(function (i) {
                var colorStr = '';
                if ($('.percent').eq(i).html() > 0) {
                    colorStr = 'red';
                } else {
                    colorStr = 'green';
                }
                $('.percent').eq(i).css('color', colorStr);
            });
        }
</script>

这里的.Percent是类名,根据类名查找元素,然后一个一个判断,如果大于0,就设置红色样式,如果小于0,就设置绿色样式。
然后在<body></body>标签中引入js函数changeColor()

<body onload="changeColor()">

删除table中的那几行判断语句,改为这样:

 <td class="percent" style="">{{.Percent}}</td>

这样就OK了,也很简单。

猜你喜欢

转载自blog.csdn.net/Charliewolf/article/details/85712480