Home > Web Front-end > JS Tutorial > Initialize components without a single js code_javascript skills

Initialize components without a single js code_javascript skills

WBOY
Release: 2016-05-16 15:17:21
Original
1613 people have browsed it

I recently discovered an usability problem when using bootstrap components. Many simple component initializations require writing a lot of initialization code in JS, such as a simple select tag, because it only needs to get data from the background to fill in the options. Inside, fetching data from the background requires js initialization, so when the page is initialized, there are many repeated codes in the js initialization code, which looks very annoying. Then I thought of the data attribute in bootstrap table. It would be great if I could use data-* directly in HTML to initialize simple components. Let’s take a look at the documentation of bootstrap table first:

You can see that almost all attributes and events in the bootstrap table can be done using data-*, which feels pretty good. Then the blogger will start researching. Where does data-* come from?

1. A preliminary study on jquery data()
After searching around on the Internet, I finally found the source of data-*. It turns out that it is in Jquery and html5. Good stuff, really good stuff! Let’s take a look at jquery’s API first

The original usage is as follows:

The function is actually very obvious, which is to add certain attributes and data to the element, or take a value.

Let’s look at the combination of data() method and html5 data-* attributes

Haha, this thing is good. The value set through the data-* of html5 can be obtained using the data() method of jquery. The rules here are as follows:

  • 1) All data attributes must start with "data-",
  • 2) Attributes are separated by "-",
  • 3) Just remove "data" and "-" when fetching attributes in jquery.

With this as the basis, we will know how to set attributes in tags, and then get the corresponding attributes in js. The following will be explained based on the example of encapsulating combobox last time.

2. jquery data() implements data-* initialization component
Still remember the previous series of JS components - encapsulating your own JS components. You can also encapsulate a simple combobox in this article, which can fetch data from the background through the URL. So below we are still doing tricks on the basis of this component to add the data-* attribute directly to the select tag to initialize the drop-down box component.

1. js component packaging code

(function ($) {
  //1.定义jquery的扩展方法combobox
  $.fn.combobox = function (options, param) {
    if (typeof options == 'string') {
      return $.fn.combobox.methods[options](this, param);
    }
    //2.将调用时候传过来的参数和default参数合并
    options = $.extend({}, $.fn.combobox.defaults, options || {});
    //3.添加默认值
    var target = $(this);
    target.attr('valuefield', options.valueField);
    target.attr('textfield', options.textField);
    target.empty();
    var option = $('<option></option>');
    option.attr('value', '');
    option.text(options.placeholder);
    target.append(option);
    //4.判断用户传过来的参数列表里面是否包含数据data数据集,如果包含,不用发ajax从后台取,否则否送ajax从后台取数据
    if (options.data) {
      init(target, options.data);
    }
    else {
      //var param = {};
      options.onBeforeLoad.call(target, options.param);
      if (!options.url) return;
      if (typeof options.param == "string"){
        options.param = JSON.parse(options.param);
      }
      $.getJSON(options.url, options.param, function (data) {
        init(target, data);
      });
    }
    function init(target, data) {
      $.each(data, function (i, item) {
        var option = $('<option></option>');
        option.attr('value', item[options.valueField]);
        option.text(item[options.textField]);
        target.append(option);
      });
      options.onLoadSuccess.call(target);
    }
    target.unbind("change");
    target.on("change", function (e) {
      if (options.onChange)
        return options.onChange(target.val());
    });
  }

  //5.如果传过来的是字符串,代表调用方法。
  $.fn.combobox.methods = {
    getValue: function (jq) {
      return jq.val();
    },
    setValue: function (jq, param) {
      jq.val(param);
    },
    load: function (jq, url) {
      $.getJSON(url, function (data) {
        jq.empty();
        var option = $('<option></option>');
        option.attr('value', '');
        option.text('请选择');
        jq.append(option);
        $.each(data, function (i, item) {
          var option = $('<option></option>');
          option.attr('value', item[jq.attr('valuefield')]);
          option.text(item[jq.attr('textfield')]);
          jq.append(option);
        });
      });
    }
  };

  //6.默认参数列表
  $.fn.combobox.defaults = {
    url: null,
    param: null,
    data: null,
    valueField: 'value',
    textField: 'text',
    placeholder: '请选择',
    onBeforeLoad: function (param) { },
    onLoadSuccess: function () { },
    onChange: function (value) { }
  };

  //这一段是新加的,在页面初始化完成之后调用初始化方法
  $(document).ready(function () {
    $('.combobox').each(function () {
      var $combobox = $(this);
      $.fn.combobox.call($combobox, $combobox.data());
    })
  });
  
})(jQuery);
大部分代码和上次的没啥区别,我们重点看看最下面这一段
  //这一段是新加的,在页面初始化完成之后调用初始化方法
  $(document).ready(function () {
    $('.combobox').each(function () {
      var $combobox = $(this);
      $.fn.combobox.call($combobox, $combobox.data());
    })
  });

Copy after login

Obviously, the component is initialized through the style selector after the page initialization is completed. Using each, if there are multiple .combobox styles, initialize each one in turn. Call the call method through $.fn.combobox.call($combobox, $combobox.data()); to call the combobox initialization. The two parameters in the call method correspond to:

  • 1) Currently initialized jquery object
  • 2) Parameter list. What you get here through $combobox.data() is the data-* attributes in all html. Pass all data-* attributes as parameters into the combobox's initialization method.

2. Initialize through data-* in html

 <select id="Search_"
     name="Search_province"
     class="form-control combobox"
     data-url="/Home/GetProvince"
     data-param='{"type":"0"}'
     data-text-field="Name"
     data-value-field="Id">
 </select>
Copy after login

Specify data-* attributes. From the above we know that the initialization here is to initialize the component through the style selector.combobox, so it is required that if you want to use data-* to initialize the component, you must set a class="combobox" style so that the background can obtain Tags that need to be initialized.

3. Backend C# method

 public class HomeController : Controller
 {
    public List<string> lstProvince = new List<string>() { "北京市", "天津市", "重庆市", "上海市", "河北省", "山西省", "辽宁省", "吉林省", "黑龙江省", "江苏省", "浙江省", "安徽省", "福建省", "江西省", "山东省", "河南省", "湖北省", "湖南省", "广东省", "海南省", "四川省", "贵州省", "云南省", "陕西省", "甘肃省", "青海省", "台湾省", "内蒙古自治区", "广西壮族自治区", "西藏自治区", "宁夏回族自治区", "新疆维吾尔自治区", "香港特别行政区", "澳门特别行政区" };

    public JsonResult GetProvince(string type)
    {
      var lstRes = new List<Province>();
      for (var i = 0; i < 10; i++)
      {
        var oModel = new Province();
        oModel.Id = i;
        oModel.Name = lstProvince[i];
        lstRes.Add(oModel);
      }
      return Json(lstRes, JsonRequestBehavior.AllowGet);
    }

  }

  public class Province
  {
    public int Id { get; set; }

    public string Name { get; set; }
  }

Copy after login

測試程式碼,沒什麼好說的。

4、調試效果


得到效果

這樣基本上就完成透過data-*來初始化元件了。

上面簡單示範了下jquery data()方法結合html5 data-*屬性的使用。基本上能達到需求:不用多寫一行js程式碼直接初始化標籤。使用的時候直接引用jquery.js和jquery.extension.js檔案即可。但我們知道既然是html5裡面的特性,那麼對瀏覽器就得有一定的要求了。當然,此用法功能比較初級,但是對於一些簡單組件的初始化就夠用了。

以上就是本文的全部內容,希望對大家的學習有所幫助。

Related labels:
js
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template