Wgzx:javascript Learning Experience--2

Source: Internet
Author: User

Share JavaScript Experience (ii)Tags: javascriptajaxweb development Htmlfirefox Framework2008-09-11 10:56 636 people read comments (0) favorite reports Classification:UI (+)

1, do not assume that struts is obsolete, and do not blindly follow the JSF and updated MVC framework, at present struts is still the best MVC framework, especially later with spring, hibernate (or Ibatis) of the Union, The application of struts has been further developed, perhaps you think Webwork2, SPRINGMVC or JSF is more excellent and practical, then there is no relationship, in fact, as long as you or your company apply, then it is.

2, do you know the TypeOf and instanceof operation in JavaScript, if you do not know, advise you to look at this knowledge, typeof return is the type of object, such as String, number, object and so on, Instanceof Determines whether an object is an instance of a class, for example:
var arr=new Array ();
var type=typeof (arr);//Return Object
var Flag=arr instanceof array;//Returns True
var Flag2=arr instanceof object;//returns true;
In the actual use process, you will find that instanceof is more powerful, of course, many times typeof is very convenient to use, but for complex occasions typeof is not very suitable, especially for custom objects and the object has a complex inheritance relationship, These can be easily judged by the use of instanceof.

3, although you may know the use of typeof in JavaScript, but if you can not do the following questions, your understanding of typeof is not enough, for example:
var A;
var rs=typeof (a);//What is the value of Rs?
(A) object (B) variable (C) undefined (D) string (E) null (F) above the answer is all incorrect
If you choose a still have some understanding of JS, if you choose b is basically a random guess, if you choose D What also can not explain, if you choose E is not clear about Java and JavaScript, choose F is not correct. The answer is C, remember that in JavaScript, if a variable is not initialized, the variable is of type undefined.

4 , maybe you've been complaining about JavaScript without lists, Hassi and stacks, queues and other data structures, if you really complain, then it is not your fault, after all, including myself, we know too little about JS, in fact, in JS, The array object itself fully supports those data structures above, for example:
  var list=new array ();//list
  list[0]= "a";
  list[100]= "B";
  var map=new Array ();//Hassi
  map["001"]= "a";
  map["username"]= "Zhangsan";
  var stack=new Array ();//Stack, that is, LIFO
  Stack.push ("a");
  Stack.pop ();
  var queue=new Array ();//queue, that is, FIFO
  Queue.unshift ("a");
  Queue.shift ();
  Visible JS is very powerful, the key is that we know too little, about JavaScript for the operation of the array, you can also refer to the "javascript operations of arrays .

5, as a web developer, we can not expect the art after the completion of the beautiful, but also for us to slice the graph, the final generation of HTML files and then to us, and then we change the HTML files to the JSP, ASP or PHP files. I have always thought that the segmentation should or best be done by our programmers themselves, because the art is actually to be applied to our products or projects, and the specific products and projects, to which parts of the need to input text, where the need for background, where the need to be able to automatically scale, And which places must be guaranteed size, there are very strict requirements, especially in our products or projects if the use of similar sitemesh, such as template technology, then transduction's work is more to be done by ourselves. This is not to say that art does not need to know HTML, CSS and other technologies, not to say that the art cut out of the figure, will not meet our requirements, we know that a picture, can have n-cut method, but to be able to meet the actual needs, often only one of the most appropriate cutting method, and this cutting method generally art is not clear Developers are also unclear, only as a developer, but also know the art of transduction people, to find the most appropriate method of segmentation, and such talent is very scarce!

6, do not be too obsessed with Ajax technology, also do not be too popular web2.0 this fashionable vocabulary, not to say anything sticky Ajax or Web2.0, can fire up or to our actual development is advantageous, if you are doing the public network website, then should notice, inappropriate Ajax use, will make the website by the search engine collects the information to reduce greatly, but the Ajax or FLEX2 and so on the user experience, is still quite good, So whether or not to use technology such as Ajax, one depends on whether your solution propaganda is useful, the other is to see whether it really improved our application.

7, for the Ajax Post submission method, you may have some questions to ask, such as the way the post is not as long as the open when the method is specified, why I put big data behind the URL, but not completely passed the past, Why I don't receive data in the background using a Request.getparamter method like JSP, we look at how Ajax sends/accepts big data in an example:

1) send.jsp: (my example uses the Ajax class library of the JavaScript Open source framework Jsjava, which encapsulates the ease of use of objects such as IE and Firefox xmlhttprequest, Unlike Prototype.js, the passed data is UrlEncode encoded by default)

var ajaxrequest=new ajaxrequest ();
Ajaxrequest.setrequestmethod ("post");
Ajaxrequest.setrequesturl ("ajaxresponse.jsp");
Ajaxrequest.setasync (TRUE);
Ajaxrequest.setmethodonsuccess (Onsuccess,[ajaxrequest]);
Ajaxrequest.setrequestheader ("Content-type", "application/x-www-form-urlencoded;charset=utf-8");
Ajaxrequest.send ("content= This is a thousands of-word document ... Omitted in this ");

To note that the setting is sent as post, the content type of the header information is set to application/x-www-form-urlencoded,charset whether to see the encoding of the content, and the big data is placed in the Send, Remember that big data is not placed in the parameters of the URL.

2) receive.jsp

InputStream Stream=request.getinputstream ();
InputStreamReader isr=new InputStreamReader (stream);
BufferedReader br=new BufferedReader (ISR);
String Str=br.readline ();
System.out.println (str);
Br.close ();

You know, for the Ajax post method submitted data, on the server side if the JSP is not simple to use getparameter can be obtained, it needs to be taken from the input stream, which is similar to the attachment upload. Of course, you should pay attention to coding and decoding problems.

8, we often use the SetTimeout method to implement timed or asynchronous operations in the interface, such as:
SetTimeout (myfunc,2000);//two seconds after executing myfunc function
However, it is important to note that the SetTimeout method does not prevent the execution of subsequent JS code logic, such as:
var a = 8;
SetTimeout (myfunc,3000);
document.write ("Wait ...");
In the above code, document.write ("Wait ..."), logic does not wait until 3 seconds to execute, but executes immediately, which may be known to most developers, but it is easy to make the following error if you are not careful, as shown in the following code:
var Ajax2hasexecuted=false;
var ajaxRequest1;
function Ajax1func () {
if (!ajax2hasexecuted) {
SetTimeout (ajax1func,200);
var text=ajaxrequest1.getresponsetext ();
var ajaxRequest2;
function Ajax2func () {
var text=ajaxrequest2.getresponsetext ();
The above code is a page to send two Ajax asynchronous requests, respectively, there are two corresponding receive operations, and business logic requirements, these two operations are to be sequential, wherein the first receive operation, need to wait for the second receive operation to complete before processing, So the first operation in the settimeout approach, the original intention is to perform the first operation of the place, the first to determine whether the second operation has been completed, if not completed, then wait 200 milliseconds, the second operation is re-executed, Then, since settimeout does not organize the subsequent logic to continue, the first operation is actually going down, leading to business errors, regardless of whether the second operation is complete. The workaround is either to add else after the if or to return directly after settimeout, for example:
if (!ajax2hasexecuted) {
SetTimeout (ajax1func,200);

9 , the window.open and window.showModalDialog methods believe that you have used many times, but there are always such or such problems, the problem is mainly the following aspects:
1) ShowModalDialog This function name is often written incorrectly, for example, is often written as showmodeldialog, which makes it impossible to perform an open window operation.
2) Controlling the properties of open windows, such as dimensions, scrollbars, menus, status bars, etc., is something we often encounter, but we often mix the property names of these two open methods with the delimiters between the attributes, so that the properties are not executed correctly, for example, I give the following example, Ask to pop a window with a width of 200 to 300, which way are you looking?
(A)   window.open ("About:blank", "" "," width=200,height=300 ");
(B)   window.open ("About:blank", "" "," width:200,height:300 ");
(C)   window.open ("About:blank", "" "," width=200;height=300 ");
(D)   window.open ("About:blank", "" "," width:200;height:300 ");
(E) window.showmodaldialog ("About:blank", "", "dialogwidth:200px;dialogheight:300px");
(F) window.showmodaldialog ("About:blank", "", "dialogwidth=200px;dialogheight=300px");
(G) window.showmodaldialog ("About:blank", "", "dialogwidth:200;dialogheight:300");
More options are not written, the correct answer is a and e, through the above questions we need to remember the points:

    • The delimiter between the window.open control attributes is a comma "," between the attribute and the value with the equals sign "=" Connection
    • The delimiter between the window.showModalDialog control attributes is a semicolon ";", with a colon ":" Connection between the attributes
    • The length and width dimensions in the window.open control attribute can be either directly written or measured, such as PX, but it is important for the length and width of the window.showmodaldialog to be prefixed with PX, otherwise the dimension is invalid.

There is a length limit for the varchar field in the database, for example, the maximum length of the Varchar2 field in oracle10g is 4000 characters, and the varchar in MySQL is 255 characters long, Note that the limit value here is a single-byte character value, and the Chinese character is a double-byte character, so for the Chinese character store, the Varchar2 field can store up to 2000 Chinese characters, and the resulting problem is the form submission verification problem in the Web development process, because for Chinese users, the input is likely to be a combination of Chinese characters and English characters, so it is important to note that the length of a string is determined by JavaScript in the following way:
var str= "abcdef";
var length=str.length;
However, this property of the string calculates the length of the independent character, for example a Chinese character is computed by length 1, so the following:
var str= "Hello";
var length=str.length;
The value of its length is 2, not 4, so how to calculate the true length of a Chinese character or a double-byte character? The search can quickly find a way to replace the Gemini character with two single-byte characters, and then calculate the length of the replaced character, of course, Jsjava provides calculation support for the true length of a double-byte string, and you can view the StringUtils class in it.

One, if you can not write out the common color of the English expression value and 16 binary representation of the value, then your HTML basic skills need to practice, such as white is black, hexadecimal is ffffff, red is the Reds, Hex is FF0000, blue Hex is 0000FF, purple is purple, orange is oranges, the commonly used gray in the web is eeeee, or lighter efefef, of course, these are not let you go back a lot of color and hexadecimal value, but master some commonly used, or very necessary.

JavaScript supports multidimensional arrays, but no constructors can directly generate multidimensional arrays, such as one-dimensional arrays that can be generated through an array, for example:
var arr=new Array (12);
Generating multidimensional arrays, although not supported by constructors, can be implemented in another way, such as implementing a 12x5 two-dimensional array:
var arr=new Array (12);
for (Var i=0;i<arr.length;i++) {
Arr[i]=new Array (5);
In addition, you can directly use Jsjava's standard class multidimensionarrayutils, which supports the generation of two-and three-dimensional arrays.

, for the IMG tag, we know that it has a align property, which controls the position of the picture with the adjacent text, and according to MSDN, the default value of this property is left, but judging from the actual display effect, It seems that this is not the case, we can compare the Align property and the align assignment to left, if the default is left, then do not write align and assign the align to leave, the effect should be the same, then let's say:
jsjava is the best JavaScript class library solution and Interface Application Development Support Framework! The
effect is as follows:

Look at the situation of joining Align=left:
jsjava is the best JavaScript class library solution and Interface Application Development Support Framework!
as follows:

from a practical point of view, the default align of IMG is not left, as if it should be bottom, and the above situation has been tested on both IE6.0 and Firefox2.0, it seems that the MSDN statement is not very credible, or you understand the wrong? You can look at the description in MSDN: http://msdn2.microsoft.com/en-us/library/ms533066.aspx

, there are several ways to add events to the interface, such as when a page is loaded, the function myfunc is executed, and several definitions are as follows:
1) Add the OnLoad event to the <body/> tag, i.e.:
<body onload= "MyFunc ()" ...;
2) define the window.onload in any place where JavaScript can be executed, namely:
3) defined in the <script/> tag:
<script For=window event=onload>
  MyFunc ();
4) Adds an event to the event queue, i.e.:
ie window.attachevent ("onload", MyFunc)
in Firefox Window.addeventlistener ("Load", Myfunc,false)
suggests a fourth approach, because there are only fourth ways to avoid overwriting other similar events, and the fourth way is to add the event to the queue of the same kind of event, Does not overwrite other similar events, this in the Web development process, it is necessary to pay special attention to, especially when we define some of the interface framework or build, often need to define the onload event, it is best to use the fourth way, because the reference interface framework and the building of the user, May also want to use the onload logic on the page, of course, the user's own use of the fourth way is not a problem, but as a responsible interface master, is not supposed to think so, we should discipline, and lenient towards others.

It is not just the body (or window) that has the OnLoad event,<iframe/> can also define the OnLoad event, as well as can define the onload event, for example, when the picture has finished loading, In the Status bar of window, the words loaded successfully are displayed:

Of course, for IMG, you'd better delve into the usage of its various events and attributes, and you'll find that there are so many things that you don't know about, and certainly a lot of developers have already studied this, but most developers lack knowledge of that.

How to add a paragraph in the HTML to keep formatted text, I believe you will think of <pre></pre> tags, for example:
This is a piece of formatted text,
The text inside will be formatted directly to the output
The results shown are:
This is a piece of formatted text,
The text inside will be formatted directly to the output

As a general rule, the pre tag is sufficient, but the pre tag's disadvantage is that it does not export the HTML tags as they are, but rather parses them, for example:
This is a formatted text, <font color= "Red" > Text inside </font> direct <br> format output
The results shown are:
This is a formatted text, the text inside will directly
Format output

So how can you export content that contains HTML as it is? In fact, there are <xmp/> tags in the HTML specification, you can achieve this effect, for example:
This is a formatted text, <font color= "Red" > Text inside </font> direct <br> format output
The results shown are:
This is a formatted text, <font color= "Red" > Text inside </font> direct <br> format output

How to get the size and coordinates of an object area is a common problem in our interface development process, we usually use the Getboundingclientrect method to get the area of the object, and then get the size and coordinates of the area. But this method can only be used in IE, of course, Firefox also has a similar approach, I believe most developers do not know, the method is getboxobjectfor, in order not to worry about cross-browser, you can directly download Jsjava, using the Getelementrectangle static methods of the Documentutils class, for example:
<script src= "Jsjava.js" ></script>
var Elemobj=document.getelementbyid ("Div1");//div1 is the ID of a div
var rect=documentutils.getelementrectangle (elemobj);//The Rect returned is the rectangle object in Jsjava
var x=rect.getx ();
var y=rect.gety ();
var width=rect.getwidth ();
var height=rect.getheight ();
Jsjava's classes and methods are tested by IE and Firefox and are easy to use.

-, the calculation and understanding of the object's position in the interface is a troublesome thing, such as ClientHeight, ClientTop, ScrollHeight, ScrollTop, offsetheight, OffsetTop, how to distinguish, What is the meaning of the position, the deep understanding of the location attributes, very helpful to the HTML interface layout of the essence of understanding, is the only way to become a master, the following is a brief introduction:
1) ClientHeight, which represents the screen height of the object area, does not contain the border dimensions of the area, but contains the dimensions of the padding
2) ClientTop, object area offsetheight half of the difference from clientheight
3) ScrollHeight, which represents the top distance from the bottom of the area of the object's contents
4) ScrollTop, which represents the height of the scroll portion of the object area, the topmost distance of the area's visible portion from the top edge of the region
5) Offsetheight, representing the screen height of the object area, including border and padding dimensions
6) OffsetTop, representing the object area distance from the previous object height
The above explanation if there is no actual experience, how much will be somewhat confused, no matter, I give you A:

Therefore, scrollheight is not always greater than or equal to clientheight, and indeed there are some developers who think that a zone is not scrolled when scrollheight and clientheight are equal, When scrolling is scrollheight=clientheight+scrolltop, the perception is incorrect or inaccurate.
The HTML source of the above diagram is:
function pos () {
Debug (Test1.clientheight);
Debug (Test1.clienttop);
Debug (Test1.scrollheight);
Debug (Test1.scrolltop);
Debug (Test1.offsetheight);
Debug (Test1.offsettop);
Debug ("--------------");
Debug (Test2.clientheight);
Debug (Test2.clienttop);
Debug (Test2.scrollheight);
Debug (Test2.scrolltop);
Debug (Test2.offsetheight);
Debug (Test2.offsettop);
Debug ("--------------");
function Debug (str) {
info.value+=str+ "/n";
<body onclick= "pos ()" >
<div id= "test1" style= "padding:5;border-width:15;border-color:black;border-

style:solid;height:100;width:200 "> Zone 1, High 100</div>
<span id= "test2" style= "height:50;width:200" > Zone 2, High 50</span>
<div id= "test4" style= "height:100;width:200; zone 4, High 100</div>
<textarea id= "Info" cols= "rows=" ></textarea>
The results shown are:

+, many people on the internet asked, how to convert an RGB color to the hexadecimal color in HTML, I saw some users of the implementation, such as the definition of a length of 256 array, and according to the law of hexadecimal to initialize it all, and some use of HTML tags some features, but there are certain limitations, In fact, as long as we understand the basic knowledge of the RGB color, the conversion is very convenient, RGB represents red (red), green (green), Blue (blue) three kinds of base colors, each of which from shallow to deep and can define 256 colors, In this way, RGB can represent 256x256x256 colors in total, and for hexadecimal color, it is actually used hexadecimal numbers to represent RGB, for example, FFFFFF for RGB (256,256,256), the conversion is very simple, is the conversion of the notation between decimal and hexadecimal, for example, RGB color RGB (132,216,12), which is represented in hexadecimal color:
132 Convert to hexadecimal digit 84
216 Convert to hexadecimal digit to D8
12 convert to hexadecimal digit 0C
So the hexadecimal color of RGB (132,216,12) is 84d80c, we can look at the effect of both:
<div style= "Width:50;height:50" ></div>
<div style= "Width:50;height:50" ></div>
Shown as:

Does JavaScript provide a conversion of decimal and hexadecimal numbers, and JavaScript does not provide built-in functions for this kind of conversion, but you can download Jsjava, using the static method of the integer class: Tohexstring method, for example
<script src= "Jsjava.js" ></script>
var hex=integer.tohexstring (253);
document.write ("<br>" +hex);//Shown as FD
Or you directly use the Color object of the Jsjava species:
var color=new color (132,216,12);
var hex=color.tohexvalue (); The value of//hex is 84d80c

in the web development process, often encounter the original page and pop-up page interaction between the problem, if it is just simple variable transfer, or is not difficult, and we often encounter a real scenario is: for example, there is a user list page, click the "New" button, pop up a page to create a user , fill out the information to submit the form and close the window, while the list page to list the new users, this time some of our developers like to use the way:
Userform.submit ();
Opener.location.reload ();//or some developers prefer to use the request URL of the opener.location= list page
Window.close ();
The above code has a very obvious problem, that is, if the form is submitted to the background, the background is still in process, and the original page has been overloaded, then the new user in the background after the storage, and will not be reflected in the list page, of course, refresh one has, but it does not reach the effect we want. Here's a more secure way to do this (not in AJAX mode):
Let the form submit, after the submission or return to the page that pops up, or a different page, and then make a judgment on the page, if the background information processing is successful, then execute the original page overload, and then close the window.
Of course some developers say that the previous way, has been used in the project has not found any problem, then I tell you, that is because you are more fortunate, the background processing speed, the list is overloaded, the background has been processed, but once the background processing slow, the customer should be trouble.

The interface problem is the current web development field (do not think it is only ASP, JSP and or PHP, etc.), Big said can include ASP. NET and Java EE, among other things, and most developers do not know how to solve interface problems, and often encounter some incredible problems. In fact, I tell you, the interface problem indeed some are very strange, but not because of this, do not go into the cause of the problem, I in the development of these years, encountered a lot of bizarre interface problems, including their own encountered and others let me to solve, but I found that in these bizarre problems behind, It is a reflection of most of our developers, in terms of interface capabilities and literacy issues, such as some people are too careless, and some people are lack of interface basic knowledge and so on. To become a master of interface is not the goal, the ability and accomplishment to solve the interface problem is the most important.

Adding an onclick operation to a connection tag is a very common way, for example:
<a href= "#" onclick= "window.open (' Yoururl ')" > People Management </a>
In general, this way is not a problem, but if the page content is longer, there is a scroll bar up and down, this way there will be some problems, mainly because of the href # cause, we know the role of the anchor is to let the page positioning and moving to the anchor, The above code Developer's intention is mainly to click on the time do not execute the link href, so write a #, but # for scrolling page, will be executed onclick at the same time, the page appears mobile positioning behavior, such a user experience is very bad, the solution has the following several:
<a href= "Javascript:void 0" onclick= "window.open (' Yoururl ')" > People Management </a>
<a href= "Javascript:return" onclick= "window.open (' Yoururl ')" > People Management </a>
It is recommended to use void 0, because the return method sometimes affects the propagation of the Click event, especially when the return is false.

in Windows XP, we often wondered why we used JavaScript to control the size and location of the window, and IE didn't support it all, such as the following code:
window.open ("About:blank", "" "," width=10000,height=15000 ");
According to reason should pop up a big window of 10000x15000, then actually the IE gives us a window that is consistent with browser size and size, why this? In fact, we understand that Microsoft, if not such restrictions, the system may be due to a large number of such code and eventually crash, of course, Microsoft's IE also provides a configuration portal, configuration restrictions, the specific entry is:

To the general site class said, the default is disabled, as long as the open on it.

in our page, we often submit the form data by post, after submission, if we refresh the page, IE will generally prompt as shown in the information:

If you avoid this hint, one is to solve the program, that is, after the form is submitted, do not continue to the window from other windows to perform location reload method, etc., preferably using the location of the href attribute or assign, replace and other methods), In the advanced options of IE, there is also an entry to set the redirect form submission when the message is given, but after the setting, there is no effect, so it is not too much to introduce.

now very popular div+css way of layout, it is true that the flexibility of the interface framework has greatly increased, can say what layout can come out, and the current Ajax way of the lightweight portal framework is basically the div+css layout of the way, But don't overdo it or use it on any occasion, for example, for a large project, it's not just about the layout, but also the many things about the interface framework, in which case it's better to use a template, in fact Div+css is a layout, and the template is a " Frame ", the two can be combined to use, as to how much can be combined, depends on your actual ability.

as a project manager, product Manager or technical director, you should pay attention to the interface aspects of the problem, think about it our current developers, most can quickly complete the background logic development, but to the interface display is stretched, the interface effect and ease of use do not in place, Interface aspects are adjusted well, the time is often not more than the background logic development with less time, I believe you have seen it, in order to debug an interface in the strange problem, often will use a person for a day or two, if you do not pay attention to the interface technology learning and literacy training, our way can go far.

Another 7788 for everyone summed up my experience in web development, especially the interface development, these are out of the way, can be counted as experience, but not necessarily the right, many things also need you to practice, test and re-summary, if I write these things, For you even if only a little use, I am very gratified, another point I need to say is that we should step out of the shadow of the master worship, do not relish in agile development, extreme programming, etc., in the face of those foreign masters, we are more important to learn their spirit and quality, Instead of being a faithful preacher, for these spirits and qualities, our Chinese nation actually has a long time, but it is now less pitiful, but it is not that we have no hope, look at the scientific community and the various industries of the national elite, look at the spirit of their bones, it is worthy of our reverence and learning.

Wgzx:javascript Learning Experience--2

Related Article

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.