作为练习,我将单页应用程序从JavaScript转换为GopherJS。
在 JS 代码中,将显示以下内容:
var list = $('.all-products .products-list');
list.find('li').on('click', function (e) {
e.preventDefault();
var productIndex = $(this).data('index');
window.location.hash = 'product/' + productIndex;
})
在我的 GopherJS 转换中,我有以下内容:
list := jquery.NewJQuery(".all-products .products-list")
list.Find("li").On("click", func(e jquery.Event) {
e.PreventDefault()
// productIndex := jquery.NewJQuery(e.Target).Data("index").(float64)
// dom.GetWindow().Location().Hash = "product/" + productIndex
})
但我正在努力弄清楚如何翻译$(this)
.jquery.NewJQuery(e.Target)
似乎没有返回li
,而是li
内部的div
。
我的理解是,函数内部的$(this)
返回作用域为外部 jQuery 项 (li
( 的this
。
对于$(this)
,你需要使用js。MakeFunc 获取对this
对象的访问权限。 类似的东西
list.Find("li").On("click", js.MakeFunc(func(this *js.Object, args []*js.Object) interface{} {
e := dom.WrapEvent(args[0])
e.PreventDefault()
productIndex := jquery.NewJQuery(this).Data("index").(float64)
dom.GetWindow().Location().Hash = "product/" + productIndex
return nil
}))