我似乎对对象的属性范围有疑问.我想将每个Message对象的title和message属性输出到select元素,但这是不起作用!我做错了什么
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! What am I doing incorrectly
<html><head> <script type="text/javascript" src="ajax.googleapis/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>我可以验证foreach实际上正在运行两次迭代,但是我无法从对象中获取值.
I can verify that the foreach is in fact running two iterations, but I cannot get the values out of the objects.
推荐答案不要使用for (c in messages).
in用于迭代对象的属性,而不用于迭代数组中的值.
in is for iterating over properties of an object, not for iterating over values in an array.
使用久经考验的
for(var i = 0; i < messages.length; i++) { ... }此外,您不会将getTitle和getMessage方法放在原型上,这是一种浪费.
Also, you are not putting your getTitle and getMessage methods on a prototype, which is kind of wasteful.
更多推荐
Javascript对象属性不在范围内
发布评论