问问题
5143 次
1 回答
4
将 HTML 插入文档后如何设置值?
HTML:
<select id="dropdown"> <option value="1">One</option> <option value="2">Two</option> <option value="3">Three</option> </select> <input id="textField" type="text" value="2" />
JavaScript:
(function() { var dropdown$ = $('#dropdown'), textField$ = $('#textField'); function changeVal() { var val = parseInt(textField$.val()); if(!!val && val > 0 && val < 4) { dropdown$.val(val); } } textField$.on('keyup', changeVal); changeVal(); })();
<option value="1" selected="selected">Text</option>
请参阅:
http ://www.w3.org/wiki/HTML/Elements/option#HTML_Attributes
http://www.w3schools.com/tags/att_option_selected.asp根据您的代码示例,我可以假设您稍后将使用此 HTML 插入某处。在这种情况下,您可以使用下一个代码:
tds.push( { content: '<select id="clientReview" name="clientReview" data-value="' + obj.get("client_review") + '">' + '<option value="1" >Hate it!</option>' + '<option value="2" >Don\'t love it but don\'t hate it.</option>' + '<option value="3" >Fantastic!</option>' + '</select>' }); function insertDropdown(td$, dropdownHTML) { var dropdown$ = $(dropdownHTML); dropdown$.val(dropdown$.data('value')); td$.html(dropdown$); } for(var i = 0, l = tds.length; i < l; i++) { insertDropdown($('#td-' + i), tds[i].content); }
于 2012-09-23T18:20:15.347 回答