更改动态添加元素的文本

时间:2012-09-10 07:27:14

标签: jquery

创建新的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 个答案:

答案 0 :(得分:1)

试试这个

$('select #option_'+id).text('New text');  //you can use html in place of text

答案 1 :(得分: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 FIDDLE

答案 2 :(得分:0)

您可以使用

将元素的内容设置为您想要的任何内容
$('#option_'+id).html('new text or html');

答案 3 :(得分: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