0

创建新的 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>
4

4 回答 4

1

像这样试试

$('select #option_'+id).text('New text');  //you can use html in place of text
于 2012-09-10T07:34:11.943 回答
1

试试这个

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) {
// the modification is here

      $('select#myselect').find('#option_'+target_id).text('New text for option ');
}

$(function() {
    addOption();
    addOption();
    addOption();
});
</script>
<head>
<body>
<select id="myselect">

</select>
<div id="buttons"></div>
</body>
</html>

JS小提琴

于 2012-09-10T08:08:15.867 回答
0

您可以将元素的内容设置为您想要使用的任何内容

$('#option_'+id).html('new text or html');
于 2012-09-10T07:30:00.107 回答
0

我已经为上述问题完成了完整的垃圾箱。所以尝试如下演示脚本链接:

演示 http://codebins.com/bin/4ldqp7g

HTML

<input type="button" id="btnadd" value="Add Option" />
<br/>
<select id="myselect">
</select>
<div id="buttons">
</div>

jQuery

var id = 0;
$(function() {
    $("#btnadd").click(function() {
        addOption();
    });
});

function addOption() {
    id += 1;
    $('#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 + '" />');
}

function changeText(target_id) {
    // Need to correction is here
    $('#myselect #option_' + target_id).text('New text for option #' + target_id);
    //OR
    // $('#myselect #option_' + target_id).html('New text for option #' + target_id);
}

演示 http://codebins.com/bin/4ldqp7g

于 2012-09-10T09:52:46.987 回答