如何使用带有javascript的'setAttribute'在选项上添加'selected'

Alb*_*uña 3 javascript

例如,我有这个,我试图默认设置option1,将默认选择,我怎么能只使用OPT.setAttribute(...,..):

 var SELECT = document.createElement('SELECT');

 var OPT1 = document.createElement('OPTION');
 OPT1.setAttribute('value', 0);

 var OPT2 = document.createElement('OPTION');
 OPT2.setAttribute('value', 0);

 OPT1.appendChild( document.createTextNode( 'option1' ) );
 OPT2.appendChild( document.createTextNode( 'option2' ) );

 SELECT.appendChild(OPT1);
 SELECT.appendChild(OPT2);
Run Code Online (Sandbox Code Playgroud)

我试着这个:

OPT1.setAttribute('selected','true'); 
Run Code Online (Sandbox Code Playgroud)

很不好意思,谢谢你的帮助.:)

Ale*_* T. 7

试试这个

var SELECT = document.createElement('SELECT');
var OPT1 = document.createElement('OPTION');
OPT1.setAttribute('value', 0);

var OPT2 = document.createElement('OPTION');
OPT2.setAttribute('value', 0);
OPT2.setAttribute('selected', 'selected');
// also you can set use .selected as a property 
// OPT2.selected = true;

OPT1.appendChild( document.createTextNode( 'option1' ) );
OPT2.appendChild( document.createTextNode( 'option2' ) );

SELECT.appendChild(OPT1);
SELECT.appendChild(OPT2);


document.getElementById('select').appendChild(SELECT);
Run Code Online (Sandbox Code Playgroud)
<div id="select"></div>
Run Code Online (Sandbox Code Playgroud)