2013-05-21 40 views
0

我有select2框克隆,现在我想连接克隆的对象与字符串,然后将其附加到目标字段。 的HTML是如何将jquery克隆对象连接到字符串

<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> 

我使用代码来初始化所述选择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); 
} 
+0

你确定在测试时你有'html()'部分?我想不出这种方法会返回一个对象的场景。另外,什么是'$('。invoice_billable_ITEMID')'选择器匹配?如果它匹配* select *元素,那么调用'html()'将返回嵌套的*选项*元素,这将不会是* td *中的有效html。 – JayPea

+0

我已经编辑过$('。invoice_billable_ITEMID')选择是针对select2的。 – Naveedumar

+0

我已编辑$('。invoice_billable_ITEMID')选择器的信息。它是用于select2框的。并且你是正确的,它没有HTML()部分,但我只是把它试图获得对象的HTML,但它只打印选择框的选项值。 – Naveedumar

回答

3

好的,你越来越近了。 .html()方法将返回一个html的字符串,除了它将返回元素的HTML(即元素的内容/子元素)的内部。为了获得元素本身的HTML,你既可以换你选择一个div内,并与您的jQuery选择匹配DIV,或者你可以用一个临时的元素做到这一点,如:

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

是包装后的工作 – Naveedumar