jquery 下拉菜单_使用jQuery和PHP创建链接的下拉菜单

jquery 下拉菜单

总览 (Overview)

链接下拉列表是其数据取决于另一个下拉列表的状态的链接。 例如,类别定义子类别,制造定义模型等。在一个下拉列表中更改值会更改链接的下拉列表中的可用项目。

The solution should be extensible, i.e. we should be able to use it on any number of drop downs.

该解决方案应该是可扩展的,即我们应该能够在任意数量的下拉菜单中使用它。

We will need a mechanism to identify the drop downs that will be the primary source of data and we need a mechanism to identify which drop down must be refreshed when the primary changes.

我们将需要一种机制来识别将成为主要数据源的下拉列表,并且我们需要一种机制来识别在主要更改时必须刷新哪些下拉列表。

To do this we will make use of a class and a custom-attribute.

为此,我们将使用一个类和一个自定义属性。

The class will be used to identify those controls that need to trigger an update when their state changes. Lets call this class linked-dropdown.

该类将用于标识状态更改时需要触发更新的那些控件。 让我们将此类称为链接下拉列表。

We use a custom data attribute to determine which dependent drop down to target when an onchange fires on the linked-dropdown. The reason behind using a custom data attribute is that it is easy to retrieve and it does not interfere with classes which should be used for styling and selecting. The data attribute we will use for this example is data-linked.

我们使用自定义数据属性来确定当onchange触发linked-dropdown时,将哪个依赖项下拉列表作为目标。 使用自定义数据属性的原因在于,它易于检索,并且不会干扰应用于样式和选择的类。 我们将在此示例中使用的data属性是数据链接的。

标记 (Markup)

在本文中,我选择使用“产品/品牌/型号”层次结构。 基于此,我们将一些标记放在一起以显示3个<select>框,我们将需要实现这些框。
  <form class="form form-horizontal">
    Get from server <input type="checkbox" name="server" id="server" /><br/>
    <div class="form-group">
      <label for="company" class="col-sm-2 control-label">Company</label>
      <div class="col-sm-10">
        <select id="company" name="company" class="form-control linked-dropdown" data-linked="make">
          <option value="">-- Select Product --</option>
          <option value="1">Product1</option>
          <option value="2">Product2</option>
          <option value="3">Product3</option>
        </select>
      </div>
    </div>
    <div class="form-group">
      <label for="make" class="col-sm-2 control-label">Make</label>
      <div class="col-sm-10">
        <select id="make" name="make" class="form-control linked-dropdown" data-linked="model"></select>
      </div>
    </div>
    <div class="form-group">
      <label for="model" class="col-sm-2 control-label">Model</label>
      <div class="col-sm-10">
        <select id="model" name="model" class="form-control"></select>
      </div>
    </div>
  </form>
image.gif
image.gif
image.gif
image.gif

Take a look at how each of the <select>'s is defined.

看一下每个<select>的定义。

Product

产品

<select id="company" name="company" class="form-control linked-dropdown" data-linked="make">

Make

使

<select id="make" name="make" class="form-control linked-dropdown" data-linked="model"></select>

Model

模型

<select id="model" name="model" class="form-control"></select>

You will notice that Product and Make are mostly the same. They both contain the .linked-dropdown class and they both have a data-linked attribute.

您会注意到Product和Make基本上相同。 它们都包含.linked-dropdown类,并且都具有数据链接属性。

The Product <select>'s data-linked attribute is set to make which happens to be the id of the Make <select>.

产品 <select>的数据链接属性设置为make ,恰好是Make <select>的ID。

The data-liked attribute for the Make <select> is set to model which happens to be the id of the model <select>.

Make <select>的类似于数据的属性设置为model ,恰好是模型<select>的ID。

You will notice that the Model <select> does not have the class or the data attribute. This is because there is nothing that is dependent on its value.

您将注意到Model <select>没有类或数据属性。 这是因为没有任何东西依赖于它的值。

数据 (The Data)

为此,我们需要数据。 具体来说,我们需要第二个(制造)和第三个(模型)<select>的数据。 我们有两个选项可以用来获取数据

Option 1

选项1

We embed the data in the JavaScript file as a data structure and do everything locally.

我们将数据作为数据结构嵌入到JavaScript文件中,并在本地进行所有操作。

Option 2

选项2

We make an AJAX call back to the server to retrieve the options for the targeted <select>

我们回拨AJAX到服务器,以检索目标<select>的选项。

Option 1 may work well with relatively small data sets, however if the data set is large it might be better to make an AJAX call back to the server.We have two options for how we source the data for the drop downs

选项1可能适用于相对较小的数据集,但是如果数据集较大,则最好向服务器进行AJAX调用。对于下拉菜单,我们有两个选择

本地数据(选项1) (Local Data (option 1))

让我们首先考虑本地数据版本。 我们需要为每个产品选项定义制造数据,并为每个产品/制造组合定义模型数据。 存储它的逻辑方法是在数组中。 这是我们将在本文中使用的样本数据集。
<script>
var options = {
  make: {
    1:{
      1: 'Prod1Make1',
      2: 'Prod1Make2',
      3: 'Prod1Make3'
    },
    2:{
      4: 'Prod2Make1',
      5: 'Prod2Make2',
      6: 'Prod2Make3'
    },
    3 :{
      7: 'Prod3Make1',
      8: 'Prod3Make2',
      9: 'Prod3Make3'
    }
  },
  model: {
    1: {
      1: 'Prod1Make1Model1',
      2: 'Prod1Make1Model2',
      3: 'Prod1Make1Model3'
    },
    2: {
      4: 'Prod1Make2Model1',
      5: 'Prod1Make2Model2',
      6: 'Prod1Make2Model3'
    },
    3: {
      7: 'Prod1Make3Model1',
      8: 'Prod1Make3Model2',
      9: 'Prod1Make3Model3'
    },
    4: {
      10: 'Prod2Make1Model1',
      11: 'Prod2Make1Model2',
      12: 'Prod2Make1Model3'
    },
    5: {
      13: 'Prod2Make2Model1',
      14: 'Prod2Make2Model2',
      15: 'Prod2Make2Model3'
    },
    6: {
      16: 'Prod2Make3Model1',
      17: 'Prod2Make3Model2',
      18: 'Prod2Make3Model3'
    },
    7: {
      19: 'Prod3Make1Model1',
      20: 'Prod3Make1Model2',
      21: 'Prod3Make1Model3'
    },
    8: {
      22: 'Prod3Make2Model1',
      23: 'Prod3Make2Model2',
      24: 'Prod3Make2Model3'
    },
    9: {
      25: 'Prod3Make3Model1',
      26: 'Prod3Make3Model2',
      27: 'Prod3Make3Model3'
    }
  }
};
</script>

As you can see this is a standard JavaScript object with two properties: one for Make and one for Model.

如您所见,这是一个具有两个属性的标准JavaScript对象:一个用于Make,一个用于Model。

Within each of these properties we define additional object properties that are made up of a key and an object with a list of values.

在每个这些属性中,我们定义其他对象属性,这些对象属性由键和具有值列表的对象组成。

The key (in the case of make) refers to the Product ID  that is linked to that set of options. So options.make[1] is the list of Makes linked to product 1.

密钥(在make的情况下)是指链接到该组选项的产品ID。 因此,options.make [1]是链接到产品1的Make的列表。

Why are we using Objects instead of arrays? This is because we cannot guarantee that Product ID's will be consecutive and start from 1. If products are a dynamically added and removed from the database it is quite feasible that the product ID's will become scattered (non-contiguous) which will not work with arrays which work of 0-based consecutive indices.

为什么我们使用对象而不是数组? 这是因为我们不能保证产品ID是连续的并从1开始。如果产品是动态添加到数据库中并从数据库中删除的,则产品ID变得分散(不连续)是不可行的,这不适用于数组从0开始的连续索引。

From the data we begin to get a picture of how this is going to work. We select a product, we use the selected Product ID to retrieve an array of Makes linked to that product and the same from Make to model.

从数据中,我们开始了解它是如何工作的。 我们选择一个产品,我们使用选定的产品ID检索链接到该产品的Make数组,并从Make到模型检索相同的Make。

JavaScript / jQuery (JavaScript / jQuery)

To make this work we need some JavaScript to link the change events on the <select> boxes to our code that will manage the options in those <select>'s. What we need to do is bind to the onchange event of any select that has the .linked-dropdown class. We then use the context information in the event handler to work out what <select> to update.

为了完成这项工作,我们需要一些JavaScript来将<select>框上的更改事件链接到我们的代码,这些代码将管理这些<select>中的选项。 我们需要做的是绑定到具有.linked-dropdown类的所有选择的onchange事件。 然后,我们在事件处理程序中使用上下文信息来确定要更新的<select>。

Before jumping in it is important to consider how this is going to function. When a <select> higher up the hierarchy changes we need to set the options in the linked <select>. But there is more to it than that. In our example we have a hierarchy 3 levels deep. When we change Product not only does Make need to be updated but all its dependent children need to be updated or cleared as well. If we don't do this and we change Product which results in the options in Make changing but we leave Model as is - it could end up in a data inconsistency.

在跳入之前,重要的是要考虑这将如何起作用。 当更高的层次结构中的<select>更改时,我们需要在链接的<select>中设置选项。 但是,不仅如此。 在我们的示例中,我们有3个层次的层次结构。 当我们更改产品时,不仅需要更新Make,还需要更新或清除其所有依赖的子级。 如果我们不这样做,那么我们更改产品,这会导致更改中的选项,但是我们将模型保留原样-这可能会导致数据不一致。

With that in mind lets look at the code we need to make this work

考虑到这一点,让我们看一下完成这项工作所需的代码

<script>
$(function() {
  $('.linked-dropdown').change(function() {
    // GET THE id OF THE NEXT DROPDOWN
    // IN THE CHAIN
    var linked = $(this).data('linked');
    
    // CREATE THE SELECTOR
    var target = '#' + linked;
  
    // EMPTY THE TARGET
    $(target).empty();
    
    // EMPTY ALL THE CHILDREN
    var child = $(target).data('linked');
    while (child) {
      $('#' + child).empty();
      child = $('#' + child).data('linked');
    }

    // GET THE SELECTED VALUE
    var val = $(this).val();
    // AND USE THIS TO GET THE CORRESPONDING
    // ARRAY OF OPTIONS
    opts = options[linked][val];
    
    // INSERT THE INSTRUCTION OPTION
    $(target).append($('<option/>').val('').html('-- Select --'));
      
    // LOOP THROUGH THE TARGET OPTIONS AND ADD THEM
    $.each(opts, function(v,o) {
      $(target).append($('<option/>').html(o).val(v))
    });
  });
});
</script>

There is quite a bit of code but the comments should give an idea of what we are doing.

有很多代码,但是注释应该让我们了解我们在做什么。

  •   First we get the id of the linked <select>

    首先,我们获得链接的<select>的ID
  •  We empty it

    我们清空
  •  We check to see if it has a dependent and empty that and so on in the loop.

    我们检查它是否具有依赖项,并在循环中将其清空,依此类推。
  •  We then get the array of options from our static object that match the selected criteria of the parent <select> and use those to add <option>'s  to the target.

    然后,我们从静态对象中获取与父<select>的选定条件匹配的选项数组,并使用这些条件将<option>添加到目标中。

服务器数据(选项2) (Server Data (option2))

如果我们想从服务器获取数据怎么办? 有两件事需要改变。

1. We need to change the script above to use an AJAX request to send the selected value to the server and receive back a list of options to add to the child.

1.我们需要更改上面的脚本,以使用AJAX请求将选定的值发送到服务器,并接收回添加到子级的选项列表。

2. We need server side code to interpret the request and build a list of items to send back.

2.我们需要服务器端代码来解释请求并构建要发送回的项目列表。

Let's look at the client side (AJAX) code first. The first part is the same as the script above - it is just in the populating section that things change.

首先让我们看一下客户端(AJAX)代码。 第一部分与上面的脚本相同-只是在填充部分中发生了变化。

$(function() {
  $('.linked-dropdown').change(function() {
    // GET THE id OF THE NEXT DROP DOWN IN THE CHAIN
    var linked = $(this).data('linked');
    
    // CREATE THE SELECTOR
    var target = '#' + linked;
  
    // EMPTY THE TARGET
    $(target).empty();
    
    // EMPTY ALL THE CHILDREN
    var child = $(target).data('linked');
    while (child) {
      $('#' + child).empty();
      child = $('#' + child).data('linked');
    }

    // EVERYTHING UP TO HERE IS UNCHANGED

    // SERVER SEND AJAX CALL AND POPULATE WITH RESPONSE
    $.ajax({
      url: 'getoptions.php',
      data: {
        linked: linked,
        value: $(this).val()
      },
      type: "POST",
      dataType: "html"
    }).then(function(resp) {
      // SERVER BUILDS HTML RETURN WE JUST INSERT IT
      $(target).html(resp);
    });
  });
});

All that is missing from the above solution is a server script to return the data. The sample script below also uses static data but the principle remains the same as if the data was retrieved from a database. The script receives an ID (value) and a target (linked) that determines which options must be returned.

上述解决方案缺少的是一个服务器脚本来返回数据。 下面的示例脚本也使用静态数据,但是其原理与从数据库中检索数据的原理相同。 该脚本接收一个ID(值)和一个目标(链接),该目标确定必须返回哪些选项。

The script runs a loop to create the <option> output and sends this back to the browser.

该脚本运行一个循环以创建<option>输出,并将其发送回浏览器。

<?php
 
$options = array (
  'make' => array (
    1 => array (
      1 => 'Server-Prod1Make1',
      2 => 'Server-Prod1Make2',
      3 => 'Server-Prod1Make3'
    ),
    2=> array (
      4=> 'Server-Prod2Make1',
      5=> 'Server-Prod2Make2',
      6=> 'Server-Prod2Make3'
    ),
    3 => array (
      7=> 'Server-Prod3Make1',
      8=> 'Server-Prod3Make2',
      9=> 'Server-Prod3Make3'
    )
  ),
  'model' => array (
    1=> array (
      1=> 'Server-Prod1Make1Model1',
      2=> 'Server-Prod1Make1Model2',
      3=> 'Server-Prod1Make1Model3'
    ),
    2=> array (
      4=> 'Server-Prod1Make2Model1',
      5=> 'Server-Prod1Make2Model2',
      6=> 'Server-Prod1Make2Model3'
    ),
    3=> array (
      7=> 'Server-Prod1Make3Model1',
      8=> 'Server-Prod1Make3Model2',
      9=> 'Server-Prod1Make3Model3'
    ),
    4=> array (
      10=> 'Server-Prod2Make1Model1',
      11=> 'Server-Prod2Make1Model2',
      12=> 'Server-Prod2Make1Model3'
    ),
    5=> array (
      13=> 'Server-Prod2Make2Model1',
      14=> 'Server-Prod2Make2Model2',
      15=> 'Server-Prod2Make2Model3'
    ),
    6=> array (
      16=> 'Server-Prod2Make3Model1',
      17=> 'Server-Prod2Make3Model2',
      18=> 'Server-Prod2Make3Model3'
    ),
    7=> array (
      19=> 'Server-Prod3Make1Model1',
      20=> 'Server-Prod3Make1Model2',
      21=> 'Server-Prod3Make1Model3'
    ),
    8=> array (
      22=> 'Server-Prod3Make2Model1',
      23=> 'Server-Prod3Make2Model2',
      24=> 'Server-Prod3Make2Model3'
    ),
    9=> array (
      25=> 'Server-Prod3Make3Model1',
      26=> 'Server-Prod3Make3Model2',
      27=> 'Server-Prod3Make3Model3'
    )
  )
);
 
$val = isset($_POST['value']) ? intval($_POST['value']) : false;
$linked = isset($_POST['linked']) ? $_POST['linked'] : false;
if ($val && $linked) {
  $opt = $options[$linked][$val];
  $return = <<< OPTION
      <option value="">-- Select --</option>
 
OPTION;
  foreach($opt as $v => $o) {
    $return .= <<< OPTION
      <option value="{$v}">{$o}</option>
OPTION;
  }
  
  echo $return;
}

You can see a working sample of the above code here

您可以在此处查看上述代码的工作示例

翻译自: https://www.experts-exchange.com/articles/28828/Creating-linked-dropdowns-using-jQuery-and-PHP.html

jquery 下拉菜单

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值