简体   繁体   English

对多个元素使用相同的 JQuery function

[英]Use a same JQuery function for multiple elements

I am currently learning web development using Flask.我目前正在使用 Flask 学习 web 开发。 I am stuck at a place where I want to use a jquery function to return the value from an input tag in for that corresponding row.我被困在一个地方,我想使用 jquery function 从输入标签中返回相应行的值。

Here;s my HTML:这是我的 HTML:

 enter code here {% extends "base.html" %} {% block title %} Menu item {% endblock %} {% block content %} <div class="container"> <div class="row"> <table class="table table-striped table-inverse table-responsive"> <thead class="thead-inverse"> <tr> <th>Item Name</th> <th>Amount</th> <th></th> </tr> </thead> <tbody> <form> {% for item in menu_category %} <tr> <td scope="row">{{item.item_Name}}</td> <td>{{item.item_Price}}</td> <td> <input type="hidden" class="form-control test" name="item_id{{ loop.index0 }}" id="itemID" placeholder="" value="{{ item.item_Id }}"> <a name="add_to_cart" id="add_to_cart" class="btn btn-primary clsAddToCart" href="#" role="button">Add to Cart</a> </td> </tr> {% endfor %} </form> </tbody> </table> </div> <p id=result>cart: </p> </div> {% endblock %}

Here's my Jquery function:这是我的 Jquery function:

    <script>
    $(function() {
        $('.clsAddToCart').bind('click', function() {
          $.getJSON('{{ url_for("func_add_to_cart") }}', {
            productID: $("input[name^='item_id']").val(),
        }, function(data) {
            $("#result").html(data.result);
        });
        return false;
        });
        });
   </script>

I just want the function to return the corresponding item id on the button click, but somehow it always returns the first item id only for all.我只希望 function 在按钮单击时返回相应的项目 id,但不知何故,它总是只为所有人返回第一个项目 id。

Much Thanks!非常感谢!

The jQuery documentation for the val method explains this on the very first line: val方法的 jQuery文档在第一行解释了这一点:

Get the current value of the first element in the set of matched elements or set the value of every matched element.获取匹配元素集中第一个元素的当前值或设置每个匹配元素的值。

(the emphasis is mine to show the relevant part for your question). (重点是我展示您问题的相关部分)。

For each "add to cart" button to work on the corresponding input, you can use $(this) to get hold of the specific button clicked on, and then use, for example, the prev method (since in your HTML the input is the immediately preceding sibling - there are slightly more sophisticated things you could do to make this more robust to changes in your HTML, but I'll let you figure those out if you need them):对于要处理相应输入的每个“添加到购物车”按钮,您可以使用$(this)来获取单击的特定按钮,然后使用例如prev方法(因为在您的 HTML 中,输入是前面的兄弟 - 你可以做一些更复杂的事情来使它对你的 HTML 的变化更加健壮,但如果你需要它们,我会让你弄清楚):

$(function() {
  $('.clsAddToCart').bind('click', function() {
    $.getJSON('{{ url_for("func_add_to_cart") }}', {
      productID: $(this).prev().val(),
    }, function(data) {
      $("#result").html(data.result);
    });
    return false;
  });
});

You are setting all input elements the same id ('itemID').您正在将所有输入元素设置为相同的 id ('itemID')。 Should be like: 'item{{ item.item_Id }}'.应该像:'item{{ item.item_Id }}'。 May be this can solve your problem.可能这可以解决您的问题。

Your jQuery function should be like:您的 jQuery function 应该是这样的:

    <script>
    $(function() {
        $('.clsAddToCart').bind('click', function() {
          $.getJSON('{{ url_for("func_add_to_cart") }}', {
            productID: $(this).closest('input').val(), //<==
        }, function(data) {
            $("#result").html(data.result);
        });
        return false;
        });
        });
   </script> 

In order to get the value of the correct input element you have to make use of the context of the click event.为了获得正确input元素的值,您必须使用单击事件的上下文。 The this keyword refers to the element that was click. this关键字指的是被点击的元素。 Therefore you can use that to target the correct input element using relative positioning to this .因此,您可以使用它来使用相对定位来定位正确的input元素this Per your structure any of the following should be fine as a replacement for $("input[name^='item_id']").val() :根据您的结构,以下任何一项都可以替代$("input[name^='item_id']").val()

$(this).siblings().val(); //OR
$(this).closest('td').find('input').val(); //OR
$(this).parent().children('input').val(); //AND SO ON AND SO FORTH

Please remember that:请记住:

  1. .bind() is deprecated as of v3, so use .on() .bind()自 v3 起已弃用,因此请使用.on()
  2. Keep all your id attributes unique and, no need to have them if you don't need them.保持你所有的 id 属性唯一,如果你不需要它们就不需要它们。

 $(function() { $('.clsAddToCart').on('click', function() { console.log( $(this).siblings().val() ); /*$.getJSON('{{ url_for("func_add_to_cart") }}', { productID: $("input[name^='item_id']").val(), }, function(data) { $("#result").html(data.result); }); return false;*/ }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="container"> <div class="row"> <table class="table table-striped table-inverse table-responsive"> <thead class="thead-inverse"> <tr> <th>Item Name</th> <th>Amount</th> <th></th> </tr> </thead> <tbody> <form> <:--{% for item in menu_category %}--> <tr> <td scope="row">Item Name 1</td> <td>100</td> <td> <input type="hidden" class="form-control test" name="item_id-1" id="itemID1" placeholder="" value="id1"> <a name="add_to_cart" id="add_to_cart" class="btn btn-primary clsAddToCart" href="#" role="button">Add to Cart</a> </td> </tr> <tr> <td scope="row">Item Name 2</td> <td>200</td> <td> <input type="hidden" class="form-control test" name="item_id-1" id="itemID2" placeholder="" value="id2"> <a name="add_to_cart" id="add_to_cart" class="btn btn-primary clsAddToCart" href="#" role="button">Add to Cart</a> </td> </tr> <tr> <td scope="row">Item Name 3</td> <td>300</td> <td> <input type="hidden" class="form-control test" name="item_id-1" id="itemID3" placeholder="" value="id3"> <a name="add_to_cart" id="add_to_cart" class="btn btn-primary clsAddToCart" href="#" role="button">Add to Cart</a> </td> </tr> <tr> <td scope="row">Item Name 4</td> <td>50</td> <td> <input type="hidden" class="form-control test" name="item_id-1" id="itemID4" placeholder="" value="id4"> <a name="add_to_cart" id="add_to_cart" class="btn btn-primary clsAddToCart" href="#" role="button">Add to Cart</a> </td> </tr> <!--{% endfor %}--> </form> </tbody> </table> </div> <p id=result>cart: </p> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM