代码之家  ›  专栏  ›  技术社区  ›  Joao Victor Souza

jquery-具有不同数组键的select字段的循环数组

  •  0
  • Joao Victor Souza  · 技术社区  · 8 年前

    我正在动态地生成一些select输入,它遵循这个结构

    <select id="OrderType_orderItem_0_product" name="OrderType[orderItem][0][product]" class="form-control">,
    
    <select id="OrderType_orderItem_1_product" name="OrderType[orderItem][1][product]" class="form-control">
    

    等等。

    我需要在上做一篇ajax文章。更改生成的每个select,我该怎么做?

    现在我有了这个,但显然它只适用于id 0的第一个选择:

    $(document).ready(function () {
            $('[name="OrderType[orderItem][0][product]"]').change(function(){
               var val = $(this).val();
               $.ajax({
                    type: "POST",
                    url: "myurl" + val,
                    success: function(data) {
    
                    }
                });
                return false;
            });
    
    2 回复  |  直到 8 年前
        1
  •  2
  •   Abderrahim Soubai-Elidrisi    8 年前

    你只需要启动函数 change 任何以 OrderType

    试试这个例子:

    $(document).ready(function () {
    
      $("select[name^='OrderType']").change(function(){
    
               var val = $(this).val();
    
               $.ajax({
                    type: "POST",
                    url: "myurl" + val,
                    success: function(data) {
    
                    }
                });
                return false;
      });
    
    });
    
        2
  •  3
  •   Budyn    8 年前

    一种方法是给他们一个共享类

    <select id="OrderType_orderItem_0_product" name="OrderType[orderItem][0][product]" class="form-control myClass">,
    
    <select id="OrderType_orderItem_1_product" name="OrderType[orderItem][1][product]" class="form-control myClass">
    

    然后将此事件分配给该类:

    $(document).ready(function () {
            $('.myClass').change(function(){
               var val = $(this).val();
               $.ajax({
                    type: "POST",
                    url: "myurl" + val,
                    success: function(data) {
    
                    }
                });
                return false;
            });
    

    因为我们对val使用这个元素,所以它将使用触发事件的元素。