DIV CSS 佈局教程網

用 jQuery 實作連動二級選單
編輯:JQuery特效代碼     

表單中常見「一級分類選好後,二級分類自動帶入」的連動效果。本文示範以 jQuery 搭配後端 Ajax,實作一個可回顯已選值的二級連動選單。

前端:查詢子選項的函數

function querySub(id, sid /* 選中的項 */) {
  $.post('${path}/page/article/querySubChannelArticle.action',
    { 'channelId': id }, function (data) {
      $('select[name="article.subChannel.subId"] option[value!=""]').remove();
      var jsonObj = data;
      for (var i = 0; i < jsonObj.length; i++) {
        var $option = $('<option>');
        $option.attr('value', jsonObj[i].subId);
        if (jsonObj[i].subId === sid) {
          $option.attr('selected', true);
        }
        $option.text(jsonObj[i].subName);
        $('select[name="article.subChannel.subId"]').append($option);
      }
    });
}

$(function () {
  querySub(<s:property value='article.subChannel.channel.channelId'/>, <s:property value='article.subChannel.subId'/>);
});

前端:頁面結構

一級欄目變更時觸發查詢,二級欄目則在頁面載入時依已選值回顯:

<tr>
  <th>一級欄目</th>
  <td valign="middle">
    <s:select id='_channel' list="channelList" listKey="channelId"
      listValue="channelName"
      key="article.subChannel.channel.channelId"
      onchange="querySub(this.value)"></s:select>
  </td>
</tr>
<tr>
  <th>二級欄目</th>
  <td valign="middle">
    <s:select name='article.subChannel.subId' list="{}" headerKey="" headerValue="-請選擇-"></s:select>
  </td>
</tr>

後端:回傳 JSON

public String querySubChannelArticle() {
  HttpServletResponse response = getResponse();
  HttpServletRequest request = getRequest();
  response.setContentType("application/json; charset=UTF-8");
  PrintWriter out = null;
  try {
    out = response.getWriter();
    List<Map<String, Object>> list = new LinkedList<Map<String, Object>>();
    if (channelId != null && !channelId.equals("")) {
      Channel tmp = new Channel();
      tmp.setChannelId(Integer.parseInt(channelId));
      subChannelList = subChannelDAO.listSubChannel(tmp);
      for (Object oo : subChannelList) {
        Map<String, Object> obj = new HashMap<String, Object>();
        SubChannel c = (SubChannel) oo;
        obj.put("subId", c.getSubId());
        obj.put("subName", c.getSubName());
        list.add(obj);
      }
    }
    String outStr = JsonUtil.toJSONStr(list);
    out.println(outStr);
  } catch (Exception e) {
    e.printStackTrace();
  }
  out.flush();
  out.close();
  return null;
}

整體邏輯相當簡潔:前端監聽一級欄目的變化發出請求,後端依 channelId 查詢並回傳 JSON,前端再動態重建二級選項。透過 sid 比對,還能在編輯時正確回顯已選項目。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved