不能 .append() 选项来选择元素 [英] Can't .append() option to select element

查看:24
本文介绍了不能 .append() 选项来选择元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 .append() 函数有疑问.

I have a problem with .append() function.

$('#add_row').on('click', function(){
    var new_row = $(row_default).clone();
    new_row.find('.col-1').text($(this).find('.ass-col-partenza').text());
    new_row.find('.col-2').text($(this).find('.ass-col-colore').text());
    new_row.find('.col-3').empty().html($select.clone());
    $table.append(new_row);
    console.log('New row added with select: ', $select);
});

$('#add_option').on('click', function(){
    var option = $('<option/>').val('Value '+idx).text('Text '+idx);
    idx++;
    // This should add options, and they should be added to DOM in future .append()
    $select.append(option);
    $('#my_table').find('.my_select').append(option);
    console.log('Added new option, new select is: ',$select);
});

这是带有简短指令列表的小提琴:http://jsfiddle.net/v15zyzxj/5/

Here is the fiddle with a short instruction list: http://jsfiddle.net/v15zyzxj/5/

我希望如果我附加一个选项,如果我附加一个新行,就会显示这一点.

I would expect that if I append an option, this is shown if I append a new row.

PS 我删除了我之前的问题,因为它变得非常混乱.

PS I deleted my previous question because it was getting pretty messy.

推荐答案

刚刚创建并添加到 $select 的新 option 元素正在被删除并添加到 >.my-select DOM 上的元素.为避免这种情况,请按照下面的建议向 $select 添加一个克隆.

The new option element just created and added to $select is being removed and added to .my-select elements on the DOM. To avoid that, add a clone to $select as suggested below.

只要改变:

$select.append(option);

致:

$select.append(option.clone());

演示

或者,您可以使用 .add() 来组合所有要附加新 option 的元素(在 DOM 或内存中),然后仅使用 .append() 无需 .clone():

Alternatively you could use .add() to combine all elements (in DOM or memory) that you want to append the new option to and then just .append() without the need to .clone():

//$select.append(option);
$('#my_table').find('.my_select').add($select).append(option);

演示

这篇关于不能 .append() 选项来选择元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆