在Backbone.js中渲染完成后根据userId状态隐藏div
实现Backbone.js中根据用户ID状态隐藏指定div的逻辑
你可以在模板渲染完成后,通过this.$el定位到目标div,再根据userId是否为空来控制它的显示状态,修改后的代码如下:
render: function() { // 声明局部变量避免全局污染 let userId = kf.helper.getUserId(); this.$el.html(this.template({})); // 替换成你实际要操作的div选择器,比如ID选择器#target-div const $targetDiv = this.$el.find('.target-div'); // 根据userId是否为空控制显示/隐藏 if (!userId) { $targetDiv.hide(); } else { $targetDiv.show(); } return this; }
补充说明:
- 必须给
userId加上let或var声明,防止变量泄漏到全局作用域 - 如果想简化代码,也可以用一行完成状态切换:
$targetDiv.toggle(!!userId);,当userId存在时显示元素,不存在时隐藏 - 注意将
.target-div替换为你实际需要操作的div的选择器(类名、ID均可)
内容的提问来源于stack exchange,提问作者Raj
相关产品推荐
相关产品推荐

