作为练习,我将单页应用程序从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)。
发布于 2018-05-31 13:30:31
对于$(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
}))https://stackoverflow.com/questions/50612165
复制相似问题