if (day = day select) in jQuery
$('<option></option>')
.attr('label', day)
.attr('value', day)
if(myDate.getDate() == day)
开发者_如何学运维 {
.attr('selected','selected')
}
.html(day)
.appendTo(daySelector);
What I want to do is run an if statement and if it is true make that day selected.
You can use an object to accomplish this:
$('<option />', {
selected: myDate.getDate() === day,
value: day,
text: day
}).appendTo(daySelector)
Here is an example of that style: http://jsfiddle.net/9hVeq/
Why not just put it in a var first ? Or am i missing something ?
var myOption = $('<option></option>').attr('label', day).attr('value', day);
if( myDate.getDate() === day )
myOption.attr('selected', 'selected');
myOption.html( day );
myOption.appendTo( daySelector );
attr
can take a function as a second parameter to determine what the value should be.
$('<option></option>').attr('label', day)
.attr('value', day)
.html(day)
.appendTo(daySelector)
.attr('selected', function() {
return (myDate.getDate() == day) ? "selected":null;
});
$('<option></option>')
.attr('label', day)
.attr('value', day)
.attr('selected',(myDate.getDate() == day))
.html(day)
.appendTo(daySelector);
Should be enough. Alternatively you could set the value on the select element that holds the options:
daySelector.val( day );
精彩评论