使用 javascript 在单击后更改按钮的文本


Change the text of a button after a click using javascript

我是javascript的新手,我遇到了代码问题:

<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<form id="add-to-cart-form">
    <div class="cart">
        <input type="hidden" name="product_code" value="prince"/>
        <input type="text" name="name" value="First Form"/>
        <button id="btn_add" type="submit">Add to Cart</button>
    </div>
</form>
<form id="add-to-cart-form">
    <div class="cart">
        <input type="hidden" name="product_code" value="lionel"/>
        <input type="text" name="name" value="Second Form"/>
        <button id="btn_add" type="submit">Add to Cart</button>
    </div>
</form>
   
<script>
    $(document).ready(function(){
        $("#add-to-cart-form").submit(function(e) {
            $("#btn_add").html('Good');
            $("input[name='name']").val('Input change');
            e.preventDefault(); // avoid to execute the actual submit of the form.
        });
    });
</script>

我的代码的目的是在提交表单时更改提交按钮,并更改提交表单的输入value。但是使用我的代码,提交第一个表单后,提交按钮会发生变化(这是正常的),第二个表单的输入字段的值会发生变化(不正常)。同样在提交第二份表格后,它根本不起作用。

对不起,我尽力使帖子清楚。我的母语不是英语。

每页
的 id 应该是唯一的试试吧:

<form id="add-to-cart-form-first">
    <div class="cart">
        <input type="hidden" name="product_code" value="prince"/>
        <input type="text" name="name" value="First Form"/>
        <button id="btn_add_first" type="submit">Add to Cart</button>
    </div>
</form>
<form id="add-to-cart-form-second">
    <div class="cart">
        <input type="hidden" name="product_code" value="lionel"/>
        <input type="text" name="name" value="Second Form"/>
        <button id="btn_add_second" type="submit">Add to Cart</button>
    </div>
</form>

<script>
    $(document).ready(function(){
        $("form").submit(function(e) {
            $(this).find("[type=submit]").html('Good');
            $(this).find("input[name='name']").val('Input change');
            e.preventDefault(); // avoid to execute the actual submit of the form.
        });
    });
</script>