开发者

Creating DOM 'option' elements with 'selected' attribute

Why does this code would work fine in jQuery 1.5 and not in jQuery 1.6? Was there a known change to how jquery creates DOM nodes between these two versions?

var birth = new Date(),
    current = new Date().getFullYear() - 13,
    year = $('select#year'),
    i = 0;
birth.setFullYear(1992, 10, 3);
while (i < 48) {
    var option = $('<option>', { 
        value: current - i,
        text: current - i,
        selected: (current - i === birth.getFullYear()) ? 'selected' : ''
    });
    year.append(option);
    i++;
}

See this working jsfiddle using 1.5 and this non-working jsfiddle using 1.6. The first only selects one option, but the second adds se开发者_StackOverflow中文版lected="selected" to every option.

Note I've only tested this in Chrome at this point.


selected: (current - i === birth.getFullYear()) ? 'selected' : ''

will generate either

selected="selected"

or

selected=""

In both of these cases, the browser considers selected set. That's because selected is a Boolean; Its mere presence signals that it should be selected.

You should use prop, which was introduced in jQuery 1.6:

var option = $('<option>', { 
        value: current - i,
        text: current - i
    }).prop('selected', current - i === birth.getFullYear());

http://jsfiddle.net/Z7umc/3/

Or, if you prefer to have it all within your object:

var option = $('<option>', { 
        value: current - i,
        text: current - i,
        selected: (current - i === birth.getFullYear())
    });


set the else part to false

var birth = new Date(),
    current = new Date().getFullYear() - 13,
    year = $('select#year'),
    i = 0;
birth.setFullYear(1992, 10, 3);
while (i < 48) {
    var option = $('<option>', {
        value: current - i,
        text: current - i,
        selected: ((current - i) === (birth.getFullYear())) ? 'selected' :false
    });
    year.append(option);
    i++;
}

here is the fiddle http://jsfiddle.net/Z7umc/4/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜