gpt4 book ai didi

javascript - 使用主干 View 在模板上动态添加 ID 和类

转载 作者:搜寻专家 更新时间:2023-11-01 04:58:11 24 4
gpt4 key购买 nike

我想将 ID 和 CLASS 属性添加到我的 View 模板中。这是我尝试但失败的方法。

$("#login").html( _.template( LoginTemplate ) );
this.loginmodel = new LoginModel();
this.loginview = new LoginView({
el: $("#loginContainer"),
model: this.loginmodel,
className: "test"
});

<div id="loginContainer">
<div id="loginForm">
<input class="user-input formContainerInput" id="username" placeholder="Username" required="required"/>
<input class="user-input formContainerInput" id="password" type="password" placeholder="Password" required="required"/>
<a class="connection-btn" data-role="button">Connection</a>
<a class="login-btn" data-role="button">Log In</a>
</div>

我想使用 View 而不是 html 本身来分配 id 和类。我将如何做?

更新

尝试 #1

loginview: function(){
$("#login").html( _.template( LoginTemplate ) );
this.loginmodel = new LoginModel();
this.loginview = new LoginView({
id: "#loginContainer",
model: this.loginmodel,
attributes:{ id:'Test', class: "myClass otherClass" }
});
},

它甚至在 aptana 中的“类”部分显示错误。

甚至在主视图上尝试过,因为上面的代码是父 View 。

var LoginView = Backbone.View.extend({
events: {
"click .login-btn": "Login",
"click .connection-btn": 'Connect',
},
initialize: function(){
//some code here
},
attributes: {
id:"test"
}
});

最佳答案

使用 View.attributes 怎么样? .

您可以指定如下内容:

attributes: {
id: "myId",
class: "myClass otherClass"
}

我没试过,但也许你也可以使用 functions 让它更加动态:

attributes: {
id: function(){ return "element-" + this.id; },
class: "myClass otherClass"
}

请注意,这只会影响 view.el DOM 元素。不会影响它的任何子元素。

已更新

上述解决方案仅在 View.el 为匿名时有效。

因此,我看到在您的具体场景中唯一可行的解​​决方案是在 initialize() 中直接通过 JavaScript 操作 View.el,如下所示:

initialize: function(){
this.$el.attr( "id", "my-id" );
this.$el.attr( "class", "myclass1 myclass2" );
},

Check the jsfiddle对于操作 View.el 属性的三种不同场景。

关于javascript - 使用主干 View 在模板上动态添加 ID 和类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10242956/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com