我有一些看起来像这样的JavaScript:
TheHTML = '<select>';
TheHTML = TheHTML + '<option value="1">first</option>'
TheHTML = TheHTML + '<option value="2">second</option>'
TheHTML = TheHTML + '</select>'
然后使用$(selector).html(TheHTML);
如果我想要选择第二个选项,我需要添加$(selector).find(select).val(2);
有没有办法生成HTML,以便select元素在添加到DOM时选择第二个值?
感谢。
答案 0 :(得分:3)
答案 1 :(得分:1)
TheHTML = '<select>';
TheHTML = TheHTML + '<option value="1">first</option>';
TheHTML = TheHTML + '<option value="2" selected>second</option>'; //notice the selected parameter
TheHTML = TheHTML + '</select>'
如果您的选项是动态生成的,您可以执行以下操作:
var selected = 3;
TheHTML = '<select>';
for ( var i = 0; i < 10; i++ ) {
TheHTML = TheHTML + '<option value="1" ' + ( i == selected ? 'selected' : '' ) + '>first</option>';
}
TheHTML = TheHTML + '</select>';
顺便说一下,制作HTML的更快方法是加入数组而不是附加到字符串:
TheHTML = [];
TheHTML.push('<select>');
TheHTML.push('<option value="1">first</option>');
TheHTML.push('<option value="2" selected>second</option>');
TheHTML.push('</select>');
TheHTML = TheHTML.join('');