0

朋友们好日子。我有一个问题......谢谢,如果你帮助我,我有几个输入到一个 div 中。我在 java 脚本中使用 Clone 函数复制了该 div(通过单击一个按钮),现在,我有两个 div。但我的问题:

1-我不知道,如何正确获取输入的值(输入的名称相同)?

2-我在 div 中有一个选择输入,通过选择选择输入的每个选项来添加或删除一些输入。现在复制 div 后,在 div2 中选择一个选项,在 div1 中创建更改...我不想要它!

<div class="levels">
    <div class="add_senario_level">
        <span>Level 1</span>
        <form>
            <select name="condition" onchange="show_div(this,'shop during');">
                <option selected="selected" disabled="disabled">choose condition</option>
                <option>shop after registration</option>
                <option>shop during</option>
            </select>
            <div id="shop_during" style="display:none;">
                <input type="number" id="shop_during_num" name="shop_during_num" placeholder="Enter number">
                <select id="shop_during_time" name="shop_during_time">
                    <option selected="selected">hour after registeration</option>
                    <option>day after registeration</option>
                    <option>week after registeration</option>
                    <option>month after registeration</option>
                </select>
            </div>
            <div>
                <button type="button" class="newLevel"> Add New Level </button>
            </div>
        </form>
    </div>
</div>

<script>
    $(document).ready(function()
    {
        $(".newLevel").click(function()
        {
            $(".add_senario_level").clone().appendTo(".levels");
        });
    });

    function show_div(obj, id)
    {
        txt = obj.options[obj.selectedIndex].text;
        if (txt.match(id))
        {
            document.getElementById("shop_during").style.display = 'block';
        }
        else
        {
            document.getElementById("shop_during").style.display = 'none';
        }
    }
</script>
4

1 回答 1

0

您可以使用 jQuery 的 find 函数来查找子元素,并使用 attr 函数来获取和设置属性值。您将希望这样做以更改输入的 id 和 name 属性并选择如下:

HTML

<input type="number" id="shop_during_num0" name="shop_during_num0" class="shop_input" placeholder="Enter number">

JavaScript

$(".newLevel").click(function()
{
    const count = $('.add_senario_level').length;
    const clone = $(`#add_senario_level${count - 1}`).clone();
    const input = clone.find(`#shop_during_num${count - 1}`);
    const select = clone.find(`#shop_during_time${count - 1}`);

    input.attr('name', `shop_during_num${count}`);
    input.attr('id', `shop_during_num${count}`);
    select.attr('name', `shop_during_time${count}`);
    select.attr('id', `shop_during_time${count}`);
    clone.appendTo(".levels");
});

在 show_div 方法中,您可以使用$(obj)引用调用该函数的 select 并显示或隐藏正确的元素

$(obj).parent().find('#shop_during').css('display', 'block');
于 2020-01-28T06:29:39.940 回答