asp.net – 如何使用JQuery动态添加div?

前端之家收集整理的这篇文章主要介绍了asp.net – 如何使用JQuery动态添加div?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我有以下html显示3个文本框和一个添加按钮:

Box ID="txtLineNumber" runat="server">Box>
    Box ID="txtQty" runat="server">Box>
    Box ID="txtItemCode" runat="server">Box>
    

用户单击添加按钮时,我想创建另一个带有行项ID的div并将其放在下一行.我创建了一个js文件,但我不知道该怎么做?

这是我到目前为止:

var itemCount = 0;

function getLineItem(number) {
    var div = document.createElement('div');

   $(div).attr("id","lineitem" + number);
   var t1 = getTextBox("txt" + number.toString() + "1");
   var t2 = getTextBox("txt" + number.toString() + "2");
   var t3 = getTextBox("txt" + number.toString() + "3");

   $(div).append(t1);
   $(div).append(t2);
   $(div).append(t3);

   return $(div);
}

function getTextBox(id) {
    var textBox = document.createElement('input');
    $(textBox).attr("id",id);
    return $(textBox);
}


var lineItemCount = 0;

   $('#imgBtnAddNewLineItem').click(function() {

    lineItemCount++;

   $('#line-item').clone().attr('id',getLineItem(lineItemCount)).appendTo('#container');
    });
});
最佳答案
$(document).ready(function() {
    $('#imgBtnAddNewLineItem').click(function() {
        $('#container').append('

更新2

像这样创建一个普通的按钮:

更新**这也更新了评论等.. **

//Count the lineItems to make sure they are unique
var lineItemCount = 0;

//On document ready 
$(document).ready(function() {
    //On button click
    $('#imgBtnAddNewLineItem').click(function(e) {
        /*
           ADD THE FOLLOWING LINE TO PREVENT THE POSTBACK
           P.S. - Make sure you pass -e- to this function... 

         */
         e.preventDefault();



         //Increase the lineitemcount
         lineItemCount++;
         //Add a new lineitem to the container,pass the lineItemCount to make sure getLineItem() can generate a unique lineItem with unique TextBox ids
         $(container).append(getLineItem(lineItemCount));
    });
});

//Create a new DIV with TextBoxes
function getLineItem(number) {
    var div = document.createElement('div');
    //Give the div a unique id

    div.setAttribute('id','lineitem_' + number);

    //pass unique values to the getTextBox() function
    var t1 = getTextBox('txt_' + number + '_1');
    var t2 = getTextBox('txt_' + number + '_2');
    var t3 = getTextBox('txt_' + number + '_3');

    div.appendChild(t1);
    div.appendChild(t2);
    div.appendChild(t3);

    return div;
}

//Create a textBox,make sure the id passed to this function is unique...
function getTextBox(id) {
    var textBox = document.createElement('input');
    textBox.setAttribute('id',id);
    textBox.setAttribute('name',id);
    return textBox;
}
原文链接:https://www.f2er.com/jquery/428833.html

猜你在找的jQuery相关文章