我正在构建一个使用比我惯用的JavaScript多一点的JavaScript的系统,所以请原谅我的天真烂漫!

我有一个带有下拉列表和四个输入框的表单:
javascript - 添加包含下拉列表和动态内容以及更多JS的div-LMLPHP

当用户从下拉列表中选择项目A时,两个字段将填充我数据库中的动态数据。如果他们选择项目B,则两个字段将重新填充数据。就像我想要的那样工作。
javascript - 添加包含下拉列表和动态内容以及更多JS的div-LMLPHP

我在该div下方有一个按钮/链接,该按钮/链接允许用户即时在其下方“添加”另一个div(无页面刷新),其中包含另一个下拉列表和四个输入框。这也行得通。用户可以从下拉列表中选择一个项目,输入框也会相应更改。
javascript - 添加包含下拉列表和动态内容以及更多JS的div-LMLPHP

当用户尝试向批次中添加第三个div(或超出初始添加的任何数字)时,就会出现问题。下拉列表将更改第一个添加的div的内容,但不会影响后续的div。我猜想这与id有关,并且可以想象英语中正在发生的事情,但是不能将其放入任何可以通过编程方式工作的事物中(由于我对JS的了解有限)。
javascript - 添加包含下拉列表和动态内容以及更多JS的div-LMLPHP

我尝试遍历代码的第二个实例以增加#item_select,#item_details和#item_price,但是这样做显然没有办法,因为它没有帮助!大声笑

这是我到目前为止编写的代码:
    

<div class="row">
    <div class="input-field white col s3">
        <select class="browser-default" id="item_select1" name="item_select1">
            <option disabled selected value="">
                Choose an item
            </option>

            <option data-description1=
            "This is the detail for the One Page - Basic item."data-price1="500" value="1">
                Basic - One-page Site
            </option>

            <option data-description1=
            "This is the detail for the Additional Basic Pages item."data-price1="100" value="2">
                Basic - Additional Page(s)
            </option>
        </select>
    </div>

    <div class="input-field white col s4">
        <input class="validate" id="item_details1" name="item_details1" type="text">
    </div>

    <div class="input-field white col s2">
        <input class="validate" id="item_price1" name="item_price1" onkeyup="sum1();" type="text" value="_"> <label for="item_price1">Price</label>
    </div>

    <div class="input-field white col s1">
        <input class="validate" id="item_qty1" onkeyup="sum1();" type="text"> <label for="item_qty1">Qty</label>
    </div>

    <div class="input-field white col s2">
        <input class="validate" id="item_total1" type="text" value="_">
        <label for="item_total1">Total</label>
    </div>
</div>

<div id="content"></div><i class="tiny material-icons" onclick="addRow()" style="margin-bottom:50px;">add_circle_outline</i><a onclick="addRow()">add another item</a>

<script>
function addRow() {
    var div = document.createElement('div');

    div.className = 'row';

    div.innerHTML = '<div class="row"><div class="input-field col s3"><select class="browser-default" name="item_select2" id="item_select2"><option value="" disabled selected>Choose an item<\/option><option data-price2="500" data-description2="This is the detail for the One Page - Basic item." value="1">Basic - One-page Site<\/option><option data-price2="100" data-description2="This is the detail for the Additional Basic Pages item." value="2">Basic - Additional Page(s)<\/option><\/select><\/div><div class="input-field white col s4"><input id="item_details2" name="item_details2" type="text" class="validate"><\/div><div class="input-field white col s2"><input id="item_price2" name="item_price2" type="text" class="validate" value="_" onkeyup="sum2();"><\/div><div class="input-field white col s1"><input id="item_qty2" type="text" class="validate" onkeyup="sum2();"><\/div><div class="input-field white col s2"><input id="item_total2" type="text" class="validate" value="_"><\/div><\/div>\
    <i class="tiny material-icons" onclick="removeRow(this)">remove_circle<\/i><a onclick="removeRow(this)" style="color:red;"> remove above row<\/a>';
    document.getElementById('content').appendChild(div);
}

function removeRow(input) {
    document.getElementById('content').removeChild(input.parentNode);
}

$(document).ready(function() {
    $("#item_select1 option").filter(function() {
        return $(this).val() == $("#item_details1").attr('data-description1');
        return $(this).val() == $("#item_price1").attr('data-price1');
    }).attr('selected', true);

    $("#item_select1").live("change", function() {
        $("#item_details1").val($(this).find("option:selected").attr("data-description1"));
        $("#item_price1").val($(this).find("option:selected").attr("data-price1"));
    });
});

function sum1() {
    var txtFirstNumberValue = document.getElementById('item_price1').value;
    var txtSecondNumberValue = document.getElementById('item_qty1').value;
    var result = parseInt(txtFirstNumberValue) * parseInt(txtSecondNumberValue);
    if (!isNaN(result)) {
        document.getElementById('item_total1').value = result;
    }
}

$("#item_select1").change(function() {
    $('#item_qty1').val('');
    $('#item_total1').val('');
});

$(document).ready(function() {
    $("#item_select2 option").filter(function() {
        return $(this).val() == $("#item_details2").attr('data-description2');
        return $(this).val() == $("#item_price2").attr('data-price2');
    }).attr('selected', true);

    $("#item_select2").live("change", function() {
        $("#item_details2").val($(this).find("option:selected").attr("data-description2"));
        $("#item_price2").val($(this).find("option:selected").attr("data-price2"));
    });
});
</script>


任何帮助,将不胜感激。再说一次,我的JavaScript技能不是最出色的,因此,一个非常简单的答案(尤其是涉及代码示例的情况)将不胜感激! :)

最佳答案

我为您提供一些建议:

1)您已经在HTML中创建了第一行,并通过JavaScript创建了其他行。在一处完成所有操作,这将使以后的代码维护更加容易。在这种情况下,我已经用JavaScript完成了所有工作。

2)使用类选择器(.item_qty)代替ID(#item_qty1),然后使用jQuery Traversing函数查找所需的标签。在这里,我经常使用.closest().find()

3)我更喜欢将JS事件处理程序与HTML代码分开,使用event delegation而不是onclick等。

4)自jQuery v1.9起,已弃用并删除了.live()事件处理程序。您可以在其位置使用.on()

这是使用这些建议(JSFiddle)的修改后的代码:

<div id="content"></div>

<i class="tiny material-icons addRowLink" style="margin-bottom:50px;">add_circle_outline</i><a class="addRowLink">add another item</a>

<script>
$(document).ready(function() {
    addRow();

    $('#content').on("change", 'select.productSelect', function() {
        $(this).closest('.row').find(".item_details").val($(this).find("option:selected").attr("data-description"));
        $(this).closest('.row').find(".item_price").val($(this).find("option:selected").attr("data-price"));
        $(this).closest('.row').find(".item_price").trigger("change");
    });

    $('#content').on('change keyup', "input.item_qty, input.item_price", function() {
        sum(this);
    });

    $(".addRowLink").on('click', function() {
        addRow();
    });

    $('#content').on('click', '.removeRowLink', function() {
        removeRow(this);
    });

});

function addRow() {
    rowNumber = $('#content .row').length + 1;

    var arr = [
        {value: '', disabled: true, selected: true, text: 'Choose an item'},
        {value: '1', "data-description": "This is the detail for the One Page - Basic item.", "data-price": 500, text: 'Basic - One-page Site'},
        {value: '2', "data-description": "This is the detail for the Additional Basic Pages item.", "data-price": 100, text: 'Basic - Additional Page(s)'},
    ];

    select = $('<select class="browser-default productSelect" name="item_select' + rowNumber + '" id="item_select' + rowNumber + '"></select>');
    $(arr).each(function() {
        select.append($("<option>", this).text(this.text));
    });

    var newRow = $('<div class="row">').append(select);

    var newhtml = '';
    newhtml += '    <div class="input-field white col s4"> \r\n';
    newhtml += '        <input class="validate item_details" name="item_details' + rowNumber + '" type="text" /> \r\n';
    newhtml += '    </div> \r\n';
    newhtml += '    <div class="input-field white col s2"> \r\n';
    newhtml += '        <input class="validate item_price" name="item_price' + rowNumber + '" type="text" value="_" /> <label for="item_price' + rowNumber + '">Price</label> \r\n';
    newhtml += '    </div> \r\n';
    newhtml += '    <div class="input-field white col s1"> \r\n';
    newhtml += '        <input class="validate item_qty" name="item_qty' + rowNumber + '" type="text" /> <label for="item_qty' + rowNumber + '">Qty</label> \r\n';
    newhtml += '    </div> \r\n';
    newhtml += '    <div class="input-field white col s2"> \r\n';
    newhtml += '        <input class="validate item_total" name="item_total' + rowNumber + '" type="text" value="_" /> \r\n';
    newhtml += '        <label for="item_total' + rowNumber + '">Total</label> \r\n';
    newhtml += '    </div> \r\n';

    newRow.append(newhtml);

    if (rowNumber > 1) {
        newRow.append('<i class="tiny material-icons removeRowLink">remove_circle</i><a class="removeRowLink" style="color:red;"> remove above row</a>');
    }

    $('#content').append(newRow);
}

function removeRow(t) {
    $(t).closest('.row').remove();
}

function sum(t) {
    row = $(t).closest('.row');
    var price = row.find('.item_price').val();
    var qty = row.find('.item_qty').val();
    var result = parseInt(price) * parseInt(qty);
    if (!isNaN(result)) {
        row.find('.item_total').val(result);
    } else {
        row.find('.item_total').val("_");
    }
}

</script>

10-05 21:05
查看更多