douqufan9148 2018-09-08 01:09
浏览 146
已采纳

将Go函数传递给html / js按钮“ onclick”响应

I am using Go's "net/http" package to pass data between the html and the backend in Go. For example, we can used the location of an image like this:

<img src={{.MyPicture}} width=200 height=auto/>

We can do the same thing to pass in functions to the html and call them:

{{if .MyBool}}
    {{.MyFunction}}
{{end}}

Now my question is: how do I set the response of a button to call my function? I would expect this to work, but it doesn't:

<button onclick={{.ShowMoreLinks}}>Show more!</button>

I get "[js] Declaration or statement expected." I've tried wrapping it in a script (both inline and in the header), but neither of these seem to work. JS can't handle the passed in variable.

  • 写回答

1条回答 默认 最新

  • doubushi0031 2018-09-08 02:00
    关注

    Actually, you're using Go's template mechanism to prepare the HTML that you send to the browser. This only fills in placeholders and ultimately only produces a string (in this case HTML) that will be sent over the network to the browser for interpretation. It's the browser that can only handle interactivity with the user via events such as "onclick". Furthermore, these events have to be Javascript code, like a JS expression or a function call:

    onclick="jsFunction()"
    

    You could make your Go template provide the function to be called in the placeholder:

    onclick="{{.JSFuncCall}}"
    

    Here ".JSFuncCall" would have to evaluate to some JS function name (and the parentheses to make the call) that you must have defined in your JS client-side code. That Javascript function could then make an XHR call to the server at some specific URL that triggers a Go handler, runs the Go code you want to run, and then returns a response that you can then handle back in the JS function.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料