创建新的 html 元素后
$('select#base_element').append('<option value="new_option" id="option_'+id+'">New option</option>');
我该怎么办:
$('#option_'+id).text('new text');
id 是一个全局变量,每次添加新选项时都会更新
下面是我正在尝试做的完整示例:
<html>
<head>
<script src="jquery.min.js"></script>
<script type="text/javascript">
var id = 0;
function addOption() {
$('#myselect').append('<option id="option_'+id+'" value="blah">blah '+id+'</option>');
$('#buttons').append('<input type="button" onclick="changeText('+id+');" value="Change text of option '+id+'" />');
id += 1;
}
function changeText(target_id) {
alert('Change Text clicked');
$('#option_'+id).text('New text for option '+target_id);
}
$(function() {
addOption();
addOption();
addOption();
});
</script>
<head>
<body>
<select id="myselect">
</select>
<div id="buttons"></div>
</body>
</html>