如何将jquery clone对象连接到string

时间:2013-05-21 22:00:52

标签: jquery jquery-select2

我克隆了select2框,现在我想用克隆字符串连接克隆对象,然后将它附加到目标字段。 html是

<select data-placeholder="Select a billable item" name="nvoice_billable_ITEMID" id="invoice_billable_ITEMID" class="invoice_billable_ITEMID">
    <option value=""></option>
    <option value="35089">Initial</option>
    <option value="35088">Standard</option>
</select>

我使用代码初始化select js代码。

 var select_billable;
$(document).ready(function() {
    select_billable = $('.invoice_billable_ITEMID').clone();
    $(".nvoice_billable_ITEMID").select2({
        allowClear: true
    });});

在函数调用add_fields上我创建了克隆对象,并在用字符串连接后将其附加到目标元素。克隆对象创建得很好,但在追加后,字符串在克隆对象的位置显示[object Object]。如何将对象与字符串连接起来以便选择框可见?

//on call add the field for item
function add_fields(item_type){
    if(item_type == "Billable"){
        //   create the clone of select2 box
        var newBillableSelect = select_billable.clone();
        //function for concate the select2 box with string and append it
        appendRow(newBillableSelect);
        //initilizing the new select2 box
        newBillableSelect.select2();   
    }else if(item_type == "Product"){
        var newProductSelect = select_product.clone();
        appendRow(newProductSelect);
        newProductSelect.select2();  
    }
}
function appendRow(selectBox){
    var tr = '<tr class="fields_group" id="fields_group_ITEMID">'+
        '<td>'+ selectBox.html() +'</td>'+
        '<td>$<input type="text" style="width: 60px" size="30" name="unit_price[]" id="unit_price"></td>'+
        '<td><input type="text" style="width: 45px" size="30" name="quantity[]" id="quantity"></td>'+
        '<td><input type="hidden" name="tax_id" id="tax_id"><label class="tax_name">N/A</label><input type="hidden" name="tax_rate[]" id="tax_rate"></td>'+
        '<td>$<input type="text" value="0.00" size="10" readonly="readonly" name="net_price" id="net_price" class="read_only_text right_align_text" style="background-color: #fff;border:none;width: 100px;box-shadow:none "></td>'+
        '<td><input type="hidden" value="false" name="net_price[]" id="net_price"><a tabindex="-1" onclick="remove_invoice_item_fields(this); return false;" href="#" class="link_red link_small">remove</a></td>'+
        '</tr>';
    $('#items_tbody').append(tr);
}

1 个答案:

答案 0 :(得分:3)

好的,你越来越近了。 .html()方法将返回html的字符串,除了它将返回元素的 inner html(即元素的内容/子元素)。为了获得元素本身的html,你可以将你的select包装在div中并将该div与你的jQuery选择器匹配,或者你可以使用临时元素来完成它,例如:

'<td>'+ $('<div>').append(selectBox).html() +'</td>'