本文适用于没有JavaScript经验的ASP.net程序员。作为ASP.net程序员,您可能已经注意到编写JavaScript代码是日常工作的重要组成部分。这是事实。在当今世界,当所有应用程序(当然包括Web应用程序)都要求超快速运行时,使用JavaScript执行尽可能多的任务-并利用客户端浏览器中的这些任务执行功能-可以减轻很多麻烦。服务器工作量。坏消息是,编写JavaScript(特别是好而简单的JavaScript)并不容易。JavaScript代码语法很复杂,特别是对于从未使用C或C#语言编写代码并且不熟悉区分大小写的源代码或区分大小写的字符串管理的VB程序员而言。而且Visual Studio的Intellisense在JavaScript中不能像在服务器代码中那样有效(在VS2008中已得到改进,但是在VS2005中,JavaScript Intellisense几乎不存在)。因此,需要一个好的JavaScript代码库。有很多方法可以使编写JavaScript代码的难度最小化。所有这一切的目的是编写一个良好的JavaScript代码库(通常称为“ common.js”)以包含在我们开发的所有或几乎所有ASP.net页面中。自然,我们每个人都会偏爱这些工具中的哪一种对我们帮助编写JavaScript有更多帮助。我将把重点放在解决该问题的3种方法上:通用实用程序函数,扩展JavaScript本机对象和编写HTML元素的包装。 通用实用程序功能 只需浏览Web,您会发现很多实用程序功能,这些功能可以简化JavaScript的编写。这是一个示例:
function $() {
var elements = new Array();
for (var i = 0; i < arguments.length; i++) {
var element = arguments[i];
if (typeof element == 'string')
element = document.getElementById(element);
if (arguments.length == 1)
return element;
elements.push(element);
}
return elements;
}
您是否厌倦了编写document.getElementById –那个笨拙的函数名-?好吧,然后尝试$()。
var anyObject = $( 'id_of_the_object' );
该$()函数不仅接受对象标识符,还接受尚未建立的事件变量作为参数,不仅简化了引用对象的方式,而且扩展了实现对象的方式。
var firstObject = $('id_of_the_object');
var secondObject = $('id_of_another_object');
var manyObjects = $('the_third_object', 'the_fourth_object', firstObject, secondObject);
现在manyObjects是指定为参数的四个对象的数组(请注意,两个参数是标识符字符串,另外两个参数是引用对象的变量)。自从问世以来,该功能已成为我最常用的功能。我在以下博客条目中找到它:http : //www.dustindiaz.com/ top-ten-Ja vaScript /。该URL是找到有用的JavaScript函数的无与伦比的起点,这些函数适合放在common.js库中的重要位置。 扩展JavaScript本机对象 我们可以通过JavaScript简化生活的另一件令人惊奇的事情是扩展其本机对象。这使我们为他们提供了令人兴奋的新功能,在许多情况下,这些功能看起来像.net对象中现有的功能一样。例如,我们将使用以下新函数扩展本机JavaScript String对象:startsWith()。听起来有点熟?是的,它是.net的System.String对象的本机.net函数,当我们可以使JavaScript字符串为我们提供相同且有用的功能时,这真是太好了。扩展JavaScript本机对象是如此简单:
native_type.prototype.your_new_function = function([arguments]) {
// your JavaScript code here
// in here, the “this” object refers to the variable in which you call the function
}
举个例子:
String.prototype.startsWith = function(chars) {
// return true when the substring of the string, starting at 0
// and taking chars.length of length be equal to chars
return (this.substr(0,chars.length) == chars);
}
由于字符串在JavaScript中区分大小写,因此您甚至可以改进该功能以使其不区分大小写:
String.prototype.startsWith = function(chars,ignoreCase) {
if(ignoreCase==true) {
return (this.toLowerCase().substr(0,chars.length) == chars.toLowerCase());
} else {
return (this.substr(0,chars.length) == chars);
}
}
好吧,我已经向您展示了方式。现在想象一下以多种方式扩展JavaScript对象:具有startsWith(),endsWith(),contains(),ltrim(),rtrim(),trim()的字符串对象...想象一下在有限且不那么容易的情况下的可能性管理JavaScript Date对象!这是一个无尽的世界,等待您探索。毫无疑问,在您的common.js中,扩展本机JavaScript对象是必不可少的。 为HTML元素编写包装器 最后,我们将讨论另一种解决JavaScript问题的方法,该方法将使我们节省有限(和宝贵)时间的时间和时间:为HTML对象编写包装器。举一个简单的例子:在JavaScript中,我们需要获取对列表对象的引用,并将一个元素添加到列表中。这是本机JavaScript方式:
//---------------------------- get a reference to the list object
var list = document.getElementById( 'id_of_the_list' );
//---------------------------- Create the new option and give it text and value
var newOption = document.createElement( 'option' );
newOption.text = 'the text';
newOption.value = 'the value';
//---------------------------- Add the new option to the list object
list.options.add(newOption);
是的,我知道,与几乎所有JavaScript一样,它可以这样简化:
//---------------------------- get a reference to the list object
var list = document.getElementById( 'id_of_the_list' );
//---------------------------- add the new option
list.options[list.length] = new Option( 'the text', 'the value' );
但是即使那样,这也更易于阅读和编写:
var list = new ListControl( 'id_of_the_list' );
list.add( 'the text', 'the value' );
正如您可能从先前的代码推断出的那样,我们创建了一个ListControl JavaScript类,该类充当本机HTML <select>标记的包装。 我们可以为ListControl类提供自然命名的方法和实用程序,这将使选择对象的工作变得更加容易。这是我在页面中经常使用的完整ListControl类的列表:
function ListControl(id) {
//get a reference to the list control (using, of course, the $() function)
var _base = $(id);
//this function is to show/hide the list control wrapped, or get its visible state
//usage:
//alert(listControlObject.visible());
//listControlObject.visible(false);
this.visible = function(newValue) {
if(newValue==undefined) {
return (_base.style.display != 'none');
} else {
_base.style.display = (newValue==true) ? '' : 'none';
}
}
//this function is to enable/disable the list control wrapped, or get its enabled state
//usage:
//alert(listControlObject.enabled());
//listControlObject.enabled(false);
this.enabled = function(newValue) {
if(newValue==undefined) {
return (!_base.disabled);
} else {
_base.disabled = (!newValue);
}
}
//this function is to get the number of elements contained in the list
this.count = function() {
return _base.options.length;
}
//this function is to clear all the elements from the list
this.clear = function() {
while(_base.options.length > 0) {
_base.options.remove(0);
}
}
//this function is to add a new element to the list. The index argument is optional;
//if not supplied, the new element adds at the end of the list
this.add = function(text,value,index) {
var oItem = document.createElement('option');
oItem.text = text;
oItem.value = value;
if((index==undefined) || (index==null)) {
try {
_base.add(oItem,null);
} catch (e) {
_base.add(oItem,_base.length);
}
} else {
_base.add(oItem,index);
}
}
//this function is to remove an element from the list based on its zero-based position
this.remove = function(index) {
_base.options.remove(index);
}
//this function is to get a concrete element based on its zero-based position. The function
//returns the native Option javasacript object, so we can access to text, value, and so on
this.item = function(index) {
return _base.options[index];
}
//this function is to sort alphabetically the elements in the list. Note that this will only
//work well when elements are text-unique and value-unique
this.sort = function() {
var texts = new Array();
for(var k=0;k<_base.options.length;k++) {
texts[k] = _base.options[k].text;
}
texts.sort();
var values = new Array();
for(var k=0;k<texts.length;k++) {
values[k] = this.valueOf(texts[k]);
}
this.clear();
for(var k=0;k<texts.length;k++) {
this.add(texts[k],values[k]);
}
}
//this function is to retrieve the text that corresponds to a concrete value
this.textOf = function(value) {
for(var k=0;k<_base.options.length;k++) {
if(_base.options[k].value==value) {
return _base.options[k].text;
}
}
return null;
}
//this function is to retrieve the value that corresponds to a concrete text
this.valueOf = function(text) {
for(var k=0;k<_base.options.length;k++) {
if(_base.options[k].text==text) {
return _base.options[k].value;
}
}
return null;
}
//this function is to know when the list contains any element with the specified text
this.containsText = function(text) {
for(var k=0;k<_base.options.length;k++) {
if(_base.options[k].text==text) {
return k;
}
}
return -1;
}
//this function is to know when the list contains any element with the specified value
this.containsValue = function(value) {
for(var k=0;k<_base.options.length;k++) {
if(_base.options[k].value==value) {
return k;
}
}
return -1;
}
}
请参阅清单中的注释,以获取有关如何使用该对象的详细文档。 结束语 就像我之前说的,我已经向您展示了方法。现在,您可以创建自己的common.js(或任何您想要的名称),并开始更轻松,更快速地编写JavaScript代码。这只是三种方式,我敢肯定,您可以找到更多,但是只有通过这三种方式,您才可以找到实用工具功能,扩展JavaScript对象和创建有用的HTML对象包装器。祝您编程愉快!