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()); }) });
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>
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; } }
測試程式碼,沒什麼好說的。
4、調試效果
得到效果
這樣基本上就完成透過data-*來初始化元件了。
上面簡單示範了下jquery data()方法結合html5 data-*屬性的使用。基本上能達到需求:不用多寫一行js程式碼直接初始化標籤。使用的時候直接引用jquery.js和jquery.extension.js檔案即可。但我們知道既然是html5裡面的特性,那麼對瀏覽器就得有一定的要求了。當然,此用法功能比較初級,但是對於一些簡單組件的初始化就夠用了。
以上就是本文的全部內容,希望對大家的學習有所幫助。

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version
Chinese version, very easy to use

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Zend Studio 13.0.1
Powerful PHP integrated development environment

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool
