javascript 元素颜色和文本的动态变化

qzlgjiam  于 2023-01-29  发布在  Java
关注(0)|答案(2)|浏览(149)

下面的脚本创建了一行新的文本框和一个按钮。但是,当单击按钮时,新字段将具有新的按钮文本和新的设计。

$(function () {
  var newRow = $(".addRows").clone();
  $("#addButton").on("click", function () {
    let row = newRow.clone().appendTo("#TextBoxesGroup tbody");
    $("tr").find("#addButton").css( "border-color", "red" );
  });
});
<table id="TextBoxesGroup">
  <tr class="addRows">
    <td>Start Date:</td>
    <td>
      <input type="text" name="StartDate[]" class="picker" value="" size="6">
    </td>
    <td>End Date:</td>
    <td>
      <input type="text" name="EndDate[]" class="picker" value="" size="6">
    </td>
    <td>
      <input type="button" id="addButton" value="add row" />
    </td>        
  </tr>
</table>
<script type = "text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

例如,创建新按钮应该与文本删除和颜色红色。感谢帮助或建议

thtygnil

thtygnil1#

我认为使用模板可以使修改元素变得更容易和更干净。这里是一个使用vanillajs https://gomakethings.com/html-templates-with-vanilla-javascript/进行基本模板化的快速指南。这允许您轻松地为您的输入传递ID。
我不确定你是想切换第二行还是想添加多行,如果你只想切换第二行而不想添加更多的行,那么只使用js的第二部分,并删除第一个模板,同样地,如果你想添加多行,你可以删除js的第二部分(目前已注解掉)和第二个模板。

(function (){
    // Interpolate function from https://gomakethings.com/html-templates-with-vanilla-javascript/
    //Lets us pass a unique id to the template
    function interpolate (str, params) {
        let names = Object.keys(params);
        let vals = Object.values(params);
        return new Function(...names, `return \`${str}\`;`)(...vals);
    }

    //Using document on click as we are adding new buttons to the DOM and want the event to trigger on them as well
    $(document).on('click', '.add-button', function () {
        let id = $('.addRows').length + 1; //Use this for our row ID
        let newRow = interpolate(row_template.innerHTML, {id}); //Generate our row html from the template
        $(this).closest('.addRows').after(newRow); //Add the html to the table
    });

    //Remove button
    $(document).on('click', '.remove-button', function () {
        $(this).closest('.addRows').remove();
    });
})();

//Use the below INSTEAD of the above for just the single extra toggling row.
/*(function (){
    //Add new row from simple template
    $(document).on('click', '.add-button', function () {
        $("#TextBoxesGroup tbody").append(row_template_single.innerHTML);
    });
    //Remove the row
    $(document).on('click', '.remove-button', function () {
        $(this).closest('.addRows').remove();
    });
})();*/
/*Style for red remove button*/
.remove-button {
    background-color: #f77;
    color: white;
}
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<table id="TextBoxesGroup">
    <tbody>

    <tr class="addRows">
        <td>Start Date:</td>
        <td>
            <input type="text" name="StartDate_1" class="picker" value="" size="6">
        </td>
        <td>End Date:</td>
        <td>
            <input type="text" name="EndDate_2" class="picker" value="" size="6">
        </td>
        <td>
            <input type="button" id="addButton_1" class="add-button" value="Add row" />
        </td>
    </tr>
    </tbody>
</table>

<!-- Template allowing to add multiple new rows with unique input names via id passed -->
<template id="row_template">
    <tr class="addRows">
        <td>Start Date:</td>
        <td>
            <input type="text" name="StartDate_${id}" class="picker" value="" size="6">
        </td>
        <td>End Date:</td>
        <td>
            <input type="text" name="EndDate_${id}" class="picker" value="" size="6">
        </td>
        <td>
            <input type="button" id="addButton_${id}" class="add-button" value="Add row" />
            <input type="button" class="remove-button" value="Remove row" />
        </td>
    </tr>
</template>

<!-- Template for just 'toggling' a second row -->
<!-- <template id="row_template_single">
    <tr class="addRows">
        <td>Start Date:</td>
        <td>
            <input type="text" name="StartDate_2" class="picker" value="" size="6">
        </td>
        <td>End Date:</td>
        <td>
            <input type="text" name="EndDate_2" class="picker" value="" size="6">
        </td>
        <td>
            <input type="button" class="remove-button" value="Remove row" />
        </td>
    </tr>
</template> -->
csbfibhn

csbfibhn2#

我注意到我前面的答案没有正确处理在其他项之间添加项,即不在列表的末尾添加项。
下面的代码将更好地处理添加和删除条目,同时保持id的顺序,而不是基于我们在JavaScript中保存和管理的数据来呈现字段。

(function () {
    $(document).ready(function () {
        field_data.init()
    })
    let field_data = {
        data: [],
        init: function () {
            this.cacheDom();
            this.bindEvents();
            this.data.push(this.getItem());
            this.renderData();
        },
        cacheDom: function () {
            this.$render_container = $('#render_container');
            this.row_template_html = $('#row_template').html();
        },
        bindEvents: function () {
            $(document).on('click', '.remove-button', this.removeItem);
            $(document).on('click', '.add-button', this.addItem);

            this.$render_container.on('change', 'input', this.inputChange);

        },
        //When an item gets added, add new empty item to the data and re-render.
        addItem: function () {
            let target = parseInt($(this).attr('data-target'));
            field_data.data.splice(target+1, 0, field_data.getItem());
            field_data.renderData();
        },
        //When an item gets removed, remove it from the data and re-render.
        removeItem: function () {
            let target = parseInt($(this).attr('data-target'));
            if (field_data.data.length > 1) { //Prevent from removing last item.
                field_data.data.splice(target, 1);
                field_data.renderData();
            }
        },
        //Get a new/empty item.
        getItem: function () {
            return {
                start_date: '',
                end_date: '',
            }
        },
        //Update the data when a value of an input changes
        inputChange: function () {
            let $this = $(this);
            let id = parseInt($this.attr('data-id'));
            let target = $this.attr('data-target');
            field_data.data[id][target] = $this.val();
        },

        //Render the data according to the template.
        renderData: function () {
            let html = '';
            for (let i = 0; i < field_data.data.length; i++) {
                //Generate our row html from the template
                html += field_data.getRowTemplate(
                    {
                        id: i,
                        start_date: field_data.data[i].start_date,
                        end_date: field_data.data[i].end_date,
                    }
                );
            }
            field_data.$render_container.html(html);
        },
        //Gets the html for a single row based on our template
        getRowTemplate: function (params) {
            let names = Object.keys(params);
            let values = Object.values(params);
            return new Function(...names, `return \`${field_data.row_template_html}\`;`)(...values);
        },
    }
})();
.remove-button {
    background-color: #f77;
    color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="TextBoxesGroup">
    <tbody id="render_container">

    </tbody>
</table>
<template id="row_template">
    <tr class="addRows">
        <td>Start Date:</td>
        <td>
            <input type="text" name="StartDate_${id}" data-id="${id}" data-target="start_date" class="picker" value="${start_date}" size="6">
        </td>
        <td>End Date:</td>
        <td>
            <input type="text" name="EndDate_${id}" data-id="${id}" data-target="end_date" class="picker" value="${end_date}" size="6">
        </td>
        <td>
            <input type="button" class="add-button" data-target="${id}" id="addButton_${id}" value="Add row"/>
            <input type="button" class="remove-button" data-target="${id}" value="Remove row"/>
        </td>
    </tr>
</template>

相关问题