开发者

if (day = day select) in jQuery

开发者 https://www.devze.com 2023-03-31 20:10 出处:网络
$(\'<option></option>\') .attr(\'label\', day) .attr(\'value\', day) if(myDate.getDate() == day)
 $('<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 );
0

精彩评论

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