[英]Javascript object property not in scope
I seem to have a problem with objects' properties' scope. 我似乎对对象的属性范围有疑问。 I would like to output each of the
Message
objects' title
and message
properties to a select
element, but it is Not Working ! 我想将每个
Message
对象的title
和message
属性输出到select
元素,但是它不起作用 ! What am I doing incorrectly 我做错了什么
<html><head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
function Message(title, message) {
this.title=title;
this.message=message;
this.getTitle = function(){
return this.title;
};
this.getMessage = function(){
return this.message;
};
}
var messages = new Array(
new Message("First Title", "This is the first message"),
new Message("Second Title", "This is another message")
);
function updateSelect () {
$("#cannedMessages_button").empty();
for (c in messages) {
// First try, with getters and setters
$("#cannedMessages_button").append($('<option>', { value : c.getMessage() , text : c.getTitle() }));
// Second try, directly
$("#cannedMessages_button").append($('<option>', { value : c.message , text : c.title }));
}
}
updateSelect();
});
</script>
</head><body>
<form><select id="cannedMessages_button"></select></form>
</body></html>
I can verify that the foreach is in fact running two iterations, but I cannot get the values out of the objects. 我可以验证foreach实际上正在运行两次迭代,但是我无法从对象中获取值。
don't use for (c in messages
). 不要
for (c in messages
)。
in
is for iterating over properties of an object, not for iterating over values in an array. in
是用于遍历对象的属性,而不是用于遍历数组中的值。
Use the tried and true 使用久经考验的真实
for(var i = 0; i < messages.length; i++) {
...
}
Also, you are not putting your getTitle
and getMessage
methods on a prototype, which is kind of wasteful. 另外,您不会将
getTitle
和getMessage
方法放在原型上,这是一种浪费。
the syntax for the for in
loop in js is : js中
for in
循环的语法是:
for(var key in obj)
{
var currentElement = obj[key];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.