ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
[TOC] ## js 绑定事件 ``` var cb js.Func cb = js.FuncOf(func(this js.Value, args []js.Value) interface{} { fmt.Println("button clicked") cb.Release() // release the function if the button will not be clicked again return nil }) js.Global().Get("document").Call("getElementById", "myButton").Call("addEventListener", "click", cb) ``` ### go 调用js 的方法 ``` c := make(chan struct{}) cb := js.FuncOf(func(this js.Value, args []js.Value) interface{} { if got := args[0].Int(); got != 42 { t.Errorf("got %#v, want %#v", got, 42) } c <- struct{}{} return nil }) defer cb.Release() js.Global().Call("setTimeout", cb, 0, 42) <-c ``` ### 操作DOM (通过id,直接获取DOM) golang code ``` package main import ( "syscall/js" ) var ( sum=0 btn js.Value input js.Value ) func add(this js.Value, args []js.Value) interface{}{ sum++ input.Set("value",sum) return nil } func main() { btn = js.Global().Get("btn") btn.Call("addEventListener","click",js.FuncOf(add)) input=js.Global().Get("val") // 防止 go 退出,不然会报错,Go program has already exited c:=make(chan struct{},1) <-c } ``` html code ``` <!DOCTYPE html> <html lang="zh-cmn-Hans"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <title>Title</title> <script src="wasm_exec.js"></script> </head> <body> <button id="btn">点击</button> <input type="text" value="" id="val"> <script> const go=new Go(); WebAssembly.instantiateStreaming(fetch("main.wasm"),go.importObject).then(async (result)=>{ await go.run(result.instance) }) </script> </body> </html> ``` 效果 ![](https://img.kancloud.cn/38/bc/38bc1aa856ba1f0cd05654a907f9b498_256x49.png)