douhao7677 2018-10-24 07:15
浏览 404
已采纳

如何从Go WebAssembly访问DOM元素属性?

I'm trying to extend the "Hello WebAssembly" example from https://github.com/golang/go/wiki/WebAssembly. As given, the example simply prints a message to the console. I wanted to add some code using syscall/js to replace the body element content.

The attempt below fails to build:

package main

import (
    "fmt"

    "syscall/js"
)

func main() {
    fmt.Println("Hello, WebAssembly!") // original example
    // I added
    doc := js.Global().Get("document")
    body := doc.Call("getElementById", "thebody")
    body.innerHTML = "Dynamic Content"
}

When I try to build with $ env GOOS=js GOARCH=wasm go build -o main.wasm I get : ./wasm.go:14:6: body.innerHTML undefined (type js.Value has no field or method innerHTML)

Not surprising when you think about it, but I don't see an example in the doc at https://godoc.org/syscall/js that explains how to get and set element properties.

  • 写回答

1条回答 默认 最新

  • douyannuo7733 2018-10-24 07:32
    关注

    To get the value of any property of some JavaScript object, use the Value.Get() method (you actually already used it when you accessed the document object by calling js.Global().Get("document")). Similarly, to set a value of a property, use Value.Set().

    The name of the property whose value to get / set is simply a Go string value, "innerHTML" in your case. The value to be set may be many of Go values (e.g. string, integer numbers, floating point numbers, bool, slices, maps etc.), the js.ValueOf() function is used to obtain a js.Value() that will be set ultimately. In your case, you may simply use the Go string value "Dynamic Content".

    doc := js.Global().Get("document")
    body := doc.Call("getElementById", "thebody")
    body.Set("innerHTML", "Dynamic Content")
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部