JS component series using the HTML tag's data property to initialize the JS component _javascript tips

Source: Internet
Author: User

Foreword: When using the bootstrap component recently found a usability problem, many simple component initialization need to write a lot of initialization code in JS, such as a simple select tag, because just need to get data from the background to fill in the option, But from the background to take the data need JS initialization, so the initialization of the page when the initialization of JS code inside a lot of duplicate code, look very upset. Then think of the bootstrap table inside the Data property, if you can directly in the HTML to use data-* this way to initialize simple components, that would be cool. Let's take a look at the documentation for bootstrap table:

You can see that almost all the properties and events in bootstrap table can be done in data-* this way, and it feels good. The blogger is about to start studying. data-* where did this stuff come from?

First, jquery data () Preliminary

Online check a lap, and finally found the source of data-*, is the original jquery and HTML5 inside, good things, really good things! Let's take a look at the jquery API first.

The original usage is as follows:

The effect is obviously to add some attributes and data to an element, or to take a value.

Here's a look at the combination of the data () method and the HTML5 data-* property

Haha, this thing is good, the value set by the HTML5 data-*, can be taken with the jquery data () method. The rules here are as follows:

1 All the data properties must start with "data-",

2 attribute is separated by "-",

3 When you take the attributes in jquery, remove the "data" and "-".

With this as a basis, we know how to set the properties in the tag, and then take the corresponding properties in JS. The following is illustrated with the example of the last encapsulated ComboBox.

Two, jquery data () Implementation data-* initialization component

Remember before JS component Series-Encapsulation of their own JS components, you can also this article contains a simple ComboBox, you can go to the background through the URL to fetch data. So here we are still fiddling with this component to initialize the Drop-down box component by adding the Data-* property directly to the select tag.

1, JS component Packaging Code

(function ($) {//1. Extension methods that define jquery combobox $.fn.combobox = function (options, param) {if (TypeOf options = ' string ')
 {return $.fn.combobox.methods[options] (this, param); //2. The arguments and default parameters that are passed in the call merge options = $.extend ({}, $.fn.combobox.defaults, Options | |
 {});
 3. Add 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. To determine whether the user passed the parameter list contains data data set, if included, do not send Ajax from the background to fetch, otherwise send Ajax from the background to fetch data 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 represents the calling 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 choose ');
  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 choose ', onbeforeload:funct

 Ion (param) {}, Onloadsuccess:function () {}, Onchange:function (value) {}}; 
  This section is new and invokes the initialization method $ (document) after page initialization completes. Ready (function () {$ ('. ComboBox '). each (function () {var $combobox = $ (this);
 $.fn.combobox.call ($combobox, $combobox. Data ());
 
})
 });
 }) (JQuery);

Most of the code is no different from the last one, and we'll focus on the bottom section.

This section is new and invokes the initialization method $ (document) after page initialization completes
 . Ready (function () {
 $ ('. ComboBox '). each (function () {
  var $ ComboBox = $ (this);
  $.fn.combobox.call ($combobox, $combobox. Data ());})
 ;

It is obvious that the component is initialized through the style selector after the page initialization is complete. Each is used, and if there are multiple. ComboBox styles, initialize each one sequentially. by $.fn.combobox.call ($combobox, $combobox. Data ()), call method is invoked to invoke ComboBox initialization, and two parameters in the call method correspond to each other:

1 The currently initialized jquery object

2) parameter list. The data-* attribute in all HTML is obtained by $combobox.data (). All data-* properties are passed as parameters into the ComboBox initialization method.

2, the HTML inside through data-* initialization

<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>

Specifies the Data-* property. From the above we know that the initialization is through the style selector. ComboBox to initialize the component, so it requires that if you want to use data-* to do the initialization of the component, you must set a class= "ComboBox" style, so that the background to get to initialize the label.

3. Background C # method

public class Homecontroller:controller
 {public
 list<string> lstprovince = new list<string> () {"Beijing City "," Tianjin "," Chongqing City "," Shanghai City "," Hebei province "," Shanxi province "," Liaoning Province, "Jilin province", "Heilongjiang province", "Jiangsu province", "Zhejiang province", "Anhui province", "Fujian province", "Jiangxi province", "Shandong province", "Henan province", "Hubei province", "Hunan province" , "Guangdong province", "Hainan Province", "Sichuan province," Guizhou province "," Yunnan province "," Shaanxi province "," Gansu province "," Qinghai province "," Taiwan Province "," Inner Mongolia Autonomous Region "," Zhuang Autonomous Region "," Tibet Autonomous Region "," Ningxia Hui Autonomous Region "," Xinjiang Uygur Autonomous Region "," Hong Kong Special Boroughs "," Macao Special Administrative Region "};

 Public Jsonresult getprovince (string type)
 {
  var lstres = new list<province> ();
  for (var i = 0; i < 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;}
 }

Test code, there is nothing to say.

4, debugging effect

Get effect

This basically completes the initialization of the component through data-*.

Third, summary

It simply demonstrates the use of the next jquery data () method combined with the HTML5 data-* attribute. Basically can achieve the demand of the blogger: do not have to write a line of JS code directly initialize the label. Refer to Jquery.js and jquery.extension.js files directly when you use them. But we know that since it is HTML5 inside the characteristics, then the browser must have a certain requirements. Of course, this usage is relatively rudimentary, but the initialization of some simple components is sufficient.

If there is a mistake in the text, please point out that the blogger would appreciate it.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.