我想:
问题(请参阅上面的代码段):
myclass*
的按钮时x [i] .myaction();未定义,因为单击按钮时 ,我评估2
var x = [{
mymessage: "this is message1",
myclass: "myclass1",
myvalue: 10,
myaction: function() {
var res = anotherfunction(mymessage, myvalue);
//do something with res
}
}, {
mymessage: "this is message2",
myclass: "myclass2",
myvalue: 20,
myaction: function() {
res = anotherfunction(mymessage, myvalue);
//do something else with res
}
}];
function anotherfunction(m, v) {
alert(m);
return v;
}
for (var i = 0, len = x.length; i < len; i++) {
$('.' + x[i].myclass).click(function() {
alert(i);
x[i].myaction();
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="myclass1">Click me1</div>
<div class="myclass2">Click me2</div>
答案 0 :(得分:2)
只需使用x.mymessage
和x.myvalue
var x = {
mymessage: "this is a message",
myclass: "myclass",
myvalue: 10,
myaction: function() {
anotherfunction(x.mymessage, x.myvalue);
}
};
function anotherfunction(m, v) {
alert(m);
}
$('.'+x.myclass).click(x.myaction)
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="myclass">Click me</div>
&#13;
答案 1 :(得分:1)
只需将其更改为以下
即可
var x = {
mymessage: "this is a message",
myclass: "myclass",
myvalue: 10,
myaction: function() {
anotherfunction(x.mymessage, x.myvalue);
}
};
function anotherfunction(m, v) {
alert(m);
}
$('.' + x.myclass).click(x.myaction);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="myclass">
hi
</div>
&#13;
希望有所帮助
答案 2 :(得分:1)
出于可重复使用的目的,您实际上应该在对象中使用this
,如
myaction: function() {
anotherfunction(this.mymessage, this.myvalue);
}
但是,您应该在事件侦听器的回调中使用适当的上下文调用它,如下所示;
var x = {
mymessage: "this is a message",
myclass: "myclass",
myvalue: 10,
myaction: function() {
anotherfunction(this.mymessage, this.myvalue);
}
};
function anotherfunction(m, v) {
alert(m);
}
$('.'+x.myclass).click(function(e){x.myaction()})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="myclass">Click me</div>
因此,根据这个问题的修改版本,我相信这是一个很好的例子来证明this
在对象数组中的可重用性。您可以安全地执行以下操作;
var x = [{
mymessage: "this is message1",
myclass: "myclass1",
myvalue: 10,
myaction: function() {
var res = anotherfunction(this.mymessage, this.myvalue);
//do something with res
}
}, {
mymessage: "this is message2",
myclass: "myclass2",
myvalue: 20,
myaction: function() {
res = anotherfunction(this.mymessage, this.myvalue);
//do something else with res
}
}];
function anotherfunction(m, v) {
alert(m);
return v;
}
for (var i = 0, len = x.length; i < len; i++) {
(function(j){
$('.' + x[j].myclass).click(function(e) {
alert(j);
x[j].myaction();
});
})(i);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="myclass1">Click me1</div>
<div class="myclass2">Click me2</div>