Home Web Front-end JS Tutorial Bootstrap must learn cascading drop-down menu every day_javascript skills

Bootstrap must learn cascading drop-down menu every day_javascript skills

May 16, 2016 pm 03:08 PM

This article will introduce the customized bootstrap cascading drop-down menu. The main application scenarios include provincial and municipal context menus, etc. Let’s take this example first. Of course, context menus in other scenarios are also applicable. To be honest, it still takes a lot of effort and time to package a universal component. The so-called universal component naturally requires careful consideration, sigh! The Bootstrap related selection compiled this time also involves a lot of knowledge points such as jquery, ajax, springMVC, etc. It can be said to be all-inclusive!

First of all, please allow me to make a small introduction on behalf of this custom component.

"Hi, hello, my name is yunm.combox.js. The name given to me by the owner is actually quite vulgar. I mainly complete the corresponding data loading by adding two custom attributes to the select component. The data request uses ajax, and the back-end data processing uses springMVC (of course other methods are also possible, just return the corresponding json data). It is very, very simple to use! ”

1. Interface effect

Of course, you can’t tell how well a component is packaged from the interface, but at least you feel it’s simple and beautiful. Well, with this impression, are you interested in continuing to read? I think the answer is yes.

2. How to use

①、procity.jsp

First, load yunm.combox.js on the page (will be introduced later. As for other bootstrap css and js, they are not within the scope of this chapter, so skip them). At the same time, create two selects. See the specific format. As follows:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

<script type="text/javascript" src="${ctx}/components/yunm/yunm.combox.js"></script>

<div class="form-group">

  <div class="row">

    <div class="col-md-6">

      <select name="province_code" class="form-control combox" ref="city_select"

        refUrl="${ctx}/procity&#63;pro_code={value}&city_code=HSLY">

      </select>

    </div>

    <div class="col-md-6">

      <select name="city_code" id="city_select" class="form-control">

      </select>

    </div>

  </div>

</div>

<script type="text/javascript">

<!--

  $(function() {

    if ($.fn.combox) {

      $("select.combox", $p).combox();

    }

  });

//-->

</script>

Copy after login

·Two select components, one is province_code and the other is city_code.
·Added two attributes to the provincial menu.
​​ ref specifies that the associated menu is the city-level menu city_select
refUrl specifies the URL for the menu to obtain data
                                                                                                                                                                                                   pro_codeas the key factor to obtain municipal data
<{> {value} , then it is a passing match.                                                                                                                                                                                                              
city_code=HSLY, mainly used to select the specified province and city menu, such as the above (Henan, Luoyang), if not selected, city_code= is empty ·class="combox" Add jquery selector for the provincial drop-down box ·The key method of executing the combox component after the page is loaded is introduced in detail below

②、yunm.combox.js Now let’s take a look at the key component content!

·通过$.extend($.fn, { combox : function() {为jquery增加一个叫combox的底层(可以查询jquery帮助文档)方法。
·通过(function($){_onchange、addHtml})(jQuery);为该组件在页面初始加载时创建两个方法onchange和addHtml,至于(function($) {})(jQuery);我想你如果不了解的话,赶紧百度吧!
·先来看combox 方法
获取ref、refUrl,通过ajax向refUrl请求省级菜单数据,当获取成功后,通过addHtml方法将json转换后的option绑定到省级菜单select上
然后呢,为省级菜单select绑定change事件,传递的参数为ref(市级菜单)、refUrl(市级数据获取的url)、$this(省级菜单,便于change事件获取对应选中项,如效果图中的河南)
通过trigger方法立即执行change事件,便于获取对应的市级菜单内容。
·再来看_onchange方法,主要是点击省级菜单时触发,用于获取市级菜单列表
refUrl,向服务端请求的URL
value,用于获取省级菜单的选中项目,然后通过该value值获取省级对应的市级菜单
$ref.empty();用于清空市级菜单
通过ajax继续获取市级菜单内容,然后通过addHtml方法添加到市级菜单中。
·addHtml方法
通过jsonEval方法对服务端传递回来的数据进行eval(eval('(' + data + ')'),如有不懂,可百度)方法处理,否则会出错。
$.each(json, function(i) {遍历json,通过jquery创建option对象,然后加入到select中。

③、ProcityController

前端介绍完了,我们回到后端进行介绍,当然了,你也可以忽略本节,因为不是所用的关联数据都通过springMVC这种方法获取,那么先预览一下代码吧!

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

package com.honzh.spring.controller;

 

import java.util.ArrayList;

import java.util.List;

 

import javax.servlet.http.HttpServletResponse;

 

import org.apache.log4j.Logger;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;

 

import com.honzh.biz.database.entity.City;

import com.honzh.biz.database.entity.Option;

import com.honzh.biz.database.entity.Provincial;

import com.honzh.common.util.JsonUtil;

import com.honzh.spring.service.CityService;

import com.honzh.spring.service.ProvincialService;

 

@Controller

@RequestMapping(value = "/procity")

public class ProcityController extends BaseController {

  private static Logger logger = Logger.getLogger(ProcityController.class);

 

  /**

   * 当传递city_code,则表明下拉框要被选中,否则不选中

   */

  @RequestMapping("")

  public void index(@RequestParam(value = "city_code", required = false) String city_code,

      @RequestParam(value = "pro_code", required = false) String pro_code, HttpServletResponse response) {

    try {

      logger.debug("获取所在地区" + city_code + ", 省" + pro_code);

 

      // 如果pro_code为””,则表明要获取城市菜单,否则获取市级菜单

      if (!pro_code.equals("")) {

        Integer pro_id = ProvincialService.getInstance().getByProvincialcode(pro_code).getId();

        List<City> citys = CityService.getInstance().getCitysByProvincialId(pro_id);

        List<Option> coptions = new ArrayList<Option>(citys.size());

 

        for (City city : citys) {

          Option coption = new Option();

          coption.setId(city.getId());

          coption.setName(city.getCname());

          coption.setValue(city.getCode());

 

          // 市级菜单被选中

          if (city_code != null && !city_code.equals("")) {

            if (city.getCode().equals(city_code)) {

              coption.setSelected("selected");

            }

          }

          coptions.add(coption);

        }

        renderJson(response, coptions);

      } else {

        List<Provincial> provincials = ProvincialService.getInstance().getProvincials();

 

        // 转换成标准的option属性(name,value,selected)

        List<Option> options = new ArrayList<Option>(provincials.size());

 

        // 被选中的省市

        // 则说明是展示页面,此时需要为省级菜单和市级菜单设置选择项

        if (city_code != null && !city_code.equals("")) {

          Provincial selected_provincial = ProvincialService.getInstance().getProvincialByCitycode(city_code);

 

          pro_code = selected_provincial.getProcode();

        } else {

          pro_code = provincials.get(0) == null &#63; "" : provincials.get(0).getProcode();

        }

 

        for (Provincial provincial : provincials) {

          Option option = new Option();

          option.setId(provincial.getId());

          option.setName(provincial.getProname());

          option.setValue(provincial.getProcode());

 

          if (!pro_code.equals("") && provincial.getProcode().equals(pro_code)) {

            option.setSelected("selected");

          }

 

          options.add(option);

        }

 

        renderJson(response, JsonUtil.toJson(options));

      }

 

    } catch (Exception e) {

      logger.error(e.getMessage());

      logger.error(e.getMessage(), e);

 

      renderJson(response, null);

    }

  }

 

}

Copy after login

@RequestParam(value = "city_code", required = false) String city_code,对于RequestParam注解,其实非常好用,这里就不多做解释,只是推广一下,固定个数的参数,用该注解更易于代码的维护。
ProvincialService类、CityService类就是两个单例,尽量把数据放置在内存当中,减少查询数据库的次数,稍候贴出来一个例子。
Option类就是单纯的封装前端option组件的关键属性,便于组件的通用化。
renderJson(response, JsonUtil.toJson(options));将数据json化后返回,稍候贴上详细代码。

④、ProvincialService.java

只贴出来代码例子,不做详细解释,毕竟不是本章重点。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

package com.honzh.spring.service;

 

import java.util.ArrayList;

import java.util.List;

 

import com.honzh.biz.database.entity.City;

import com.honzh.biz.database.entity.Provincial;

import com.honzh.biz.database.mapper.ProvincialMapper;

import com.honzh.common.spring.SpringContextHolder;

 

public class ProvincialService {

 

  private static Object lock = new Object();

  private static ProvincialService config = null;

 

  private ProvincialService() {

    provincials = new ArrayList<Provincial>();

 

    ProvincialMapper mapper = SpringContextHolder.getBean(ProvincialMapper.class);

    provincials.addAll(mapper.getProvincials());

  }

 

  public static ProvincialService getInstance() {

    synchronized (lock) {

      if (null == config) {

        config = new ProvincialService();

      }

    }

    return (config);

  }

 

  public Provincial getByProvincialcode(String provincial_code) {

    for (Provincial provincial : provincials) {

      if (provincial.getProcode().equals(provincial_code)) {

        return provincial;

      }

    }

    return null;

  }

 

  private List<Provincial> provincials = null;

 

  public List<Provincial> getProvincials() {

    return provincials;

  }

 

  public Provincial getProvincialByCitycode(String city_code) {

    City city = CityService.getInstance().getCityByCode(city_code);

 

    for (Provincial provincial : provincials) {

      if (provincial.getId().intValue() == city.getProid().intValue()) {

        return provincial;

      }

    }

    return null;

  }

 

  public Provincial getProvincialByCode(String province_code) {

    for (Provincial provincial : provincials) {

      if (provincial.getProcode().equals(province_code)) {

        return provincial;

      }

    }

    return null;

  }

 

}

Copy after login

⑤、renderJson方法

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

/**

 * 如果出错的话,response直接返回404

 */

protected void renderJson(HttpServletResponse response, Object responseObject) {

  PrintWriter out = null;

  try {

    if (responseObject == null) {

      response.sendError(404);

      return;

    }

    // 将实体对象转换为JSON Object转换

    String responseStr = JsonUtil.toJson(responseObject);

    response.setCharacterEncoding("UTF-8");

    response.setContentType("application/json; charset=utf-8");

 

    out = response.getWriter();

    out.append(responseStr);

 

    logger.debug("返回是:" + responseStr);

  } catch (IOException e) {

    logger.error(e.getMessage());

    logger.error(e.getMessage(), e);

  } finally {

    if (out != null) {

      out.close();

    }

  }

}

Copy after login

以上就是本文的全部内容,希望对大家的学习有所帮助。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

TypeScript for Beginners, Part 2: Basic Data Types TypeScript for Beginners, Part 2: Basic Data Types Mar 19, 2025 am 09:10 AM

Once you have mastered the entry-level TypeScript tutorial, you should be able to write your own code in an IDE that supports TypeScript and compile it into JavaScript. This tutorial will dive into various data types in TypeScript. JavaScript has seven data types: Null, Undefined, Boolean, Number, String, Symbol (introduced by ES6) and Object. TypeScript defines more types on this basis, and this tutorial will cover all of them in detail. Null data type Like JavaScript, null in TypeScript

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

Can PowerPoint run JavaScript? Can PowerPoint run JavaScript? Apr 01, 2025 pm 05:17 PM

JavaScript can be run in PowerPoint, and can be implemented by calling external JavaScript files or embedding HTML files through VBA. 1. To use VBA to call JavaScript files, you need to enable macros and have VBA programming knowledge. 2. Embed HTML files containing JavaScript, which are simple and easy to use but are subject to security restrictions. Advantages include extended functions and flexibility, while disadvantages involve security, compatibility and complexity. In practice, attention should be paid to security, compatibility, performance and user experience.

See all articles