开发者

jQuery: Concatenation Results in Undefined

开发者 https://www.devze.com 2023-01-27 06:14 出处:网络
I\'m trying to display 10 opti开发者_如何转开发on tags in a select. The notaDt.text() is the current value. So if that value matches the i, the displays a \"selected\".

I'm trying to display 10 opti开发者_如何转开发on tags in a select. The notaDt.text() is the current value. So if that value matches the i, the displays a "selected".

var n, select, option;              
for(var i=10; i>=1; i--) {  
    n = notaDt.text();
    select = ( i == n ? "selected" : "");
    option = option + '<option value="' + i + '" ' + select + ' >' + i + '</option>';
}

The problem is with the option = option + ... It returns " undefined" when it's called (as seen below), but everything works fine.

http://img821.imageshack.us/img821/2951/screenshot20101129at749.png

Are there any other concatenation methods I could try to not get this message? Thanks!


You need to start with an empty string for option, like this:

var n, select, option = "";  

Otherwise the first time you concatenate with option (at that point, being undefined) you get "undefined" to start your string off with, as you get the toString result of undefined.


You need to set option to an initial blank string - like this:

var n, select, option = "";

And why not use += instead of option = option + - that's just my opinion.


Initially option is undefined until the first concatenation. Why don't you set it initially to an empty string?

var n, select;
var option = "";
for(var i=10; i>=1; i--) {  
    n = notaDt.text();
    select = ( i == n ? "selected" : "");
    option = option + '<option value="' + i + '" ' + select + ' >' + i + '</option>';
}
0

精彩评论

暂无评论...
验证码 换一张
取 消