Preface: Recently, when I was using the bootstrap component, I found a problem of ease of use. Many simple component initialization requires writing a lot of initialization code in JS, such as a simple select tag. Because it only needs to obtain data from the background and fill it into the option, but getting data from the background requires js initialization, so it causes a lot of duplicate code in the js initialization code when the page is initialized, which looks very annoying. So I remembered the data attribute in the bootstrap table. It would be so cool if I could use data-* to initialize simple components directly in the html. Let's first look at the bootstrap table documentation:
You can see that almost all the properties and events in the bootstrap table can be used in data-*, which feels pretty good. Then the blogger will start researching. data-*Where does this thing come from?
1. A preliminary study on jquery data()
After searching online, I finally found the source of data-*. It turned out to be from Jquery and html5. Good things, really good things! Let's take a look at the jquery API
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 values.
Let's take a look at the combination of the data() method and the html5 data-* attribute
Haha, this thing is good. The value set by html5 data-* can be obtained using jquery's data() method. The rules here are as follows:
1) All data attributes must start with "data-",
2) The attributes are separated by "-",
3) When taking attributes in jquery, just remove "data" and "-".
With this as the basis, we know how to set properties in the tag and then take the corresponding properties in js. Let’s explain it below in combination with the example of last encapsulation of combobox.
2. jquery data() implements data-* initialization component
Remember the previous JS component series - encapsulating your own JS components. You can also encapsulate a simple combobox in this article, which can fetch data from the backend through the URL. So below, we will still do our best to the basis of this component, and directly add the data-* attribute to the select tag to initialize the drop-down box component.
1. JS component encapsulation code
(function ($) { //1. Define jquery extension method combobox $.fn.combobox = function (options, param) { if (typeof options == 'string') { return $.fn.combobox.methods[options](this, param); } //2. Merge the parameters passed in when calling and default parameters options = $.extend({}, $.fn.combobox.defaults, options || {}); //3. Add the default value 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. Determine whether the parameter list sent by the user contains data data data set. If it is included, do not send ajax to fetch data from the background, otherwise send ajax to fetch data from the background 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. If the string is passed, it means calling the method. $.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('Please select'); 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. Default parameter list $.fn.combobox.defaults = { url: null, param: null, data: null, valueField: 'value', textField: 'text', placeholder: 'Please select', onBeforeLoad: function (param) { }, onLoadSuccess: function () { }, onChange: function (value) { } }; //This paragraph is newly added, and the initialization method $(document).ready(function () { $('.combobox').each(function () { var $combobox = $(this); $.fn.combobox.call($combobox, $combobox.data()); }) }); })(jQuery);Most of the codes are no different from the last one. Let's focus on the following paragraph
//This paragraph is newly added. After the page initialization is completed, the initialization method $(document).ready(function () { $('.combobox').each(function () { var $combobox = $(this); $.fn.combobox.call($combobox, $combobox.data()); }) });It is obvious that after the page initialization is completed, the component is initialized through the style selector. Each is used, if there are multiple .combobox styles, de-initialize each one in turn. Call the call method to call the initialization of combobox through $.fn.combobox.call($combobox, $combobox.data());. The two parameters in the call method correspond to:
1) The currently initialized jquery object
2) Parameter list. Here, the data-* attributes obtained through $combobox.data() are all the html data-* attributes. Pass all data-* attributes as parameters into the initialization method of combobox.
2. Initialize in html through data-*
<select id="Search_" name="Search_province" data-url="/Home/GetProvince" data-param='{"type":"0"}' data-text-field="Name" data-value-field="Id"> </select>Specify the data-* attribute. 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 the tags that need to be initialized.
3. Backend C# method
public class HomeController : Controller { public List<string> lstProvince = new List<string>() { "Beijing", "Tianjin", "Chongqing", "Shanghai", "Hebei", "Shanxi", "Liaoning", "Jilin", "Heilongjiang", "Jiangsu", "Zhejiang", "Anhui", "Fujian", "Jiangxi", "Shandong", "Henan", "Hubei", "Hunan", "Guangdong", "Hainan", "Sichuan", "Guizhou", "Yunnan", "Yannan", "Shaanxi", "Gansu", "Qinghai Province", "Taiwan Province", "Inner Mongolia Autonomous Region", "Guangxi Zhuang Autonomous Region", "Tibet Autonomous Region", "Ningxia Hui Autonomous Region", "Xinxia Uygur Autonomous Region", "Hong Kong Special Administrative Region", "Macao Special Administrative Region" }; 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; } }There is nothing to say about testing the code.
4. Debugging effect
Get the effect
This basically completes the initialization of the component through data-*.
3. Summary
The above briefly demonstrates the use of the jquery data() method combined with the html5 data-* attribute. It can basically meet the needs of bloggers: you don’t need to write one more line of js code to initialize the tag directly. When using it, just refer to the jquery.js and jquery.extension.js files. But we know that since it is a feature in html5, there must be certain requirements for the browser. Of course, this usage function is relatively basic, but it is enough for the initialization of some simple components.
If there is any incorrect understanding in the article, please point it out, and the blogger will be very grateful.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.