Java Scripting language learning experience

Source: Internet
Author: User
Tags jquery library

The first technology blog, must be serious!

The first technology blog, must be serious!

The first technology blog, must be serious!

Okay, get to the point:

What is a scripting language?

There are two ways to run a program: Compile run and interpret run

1.1

The typical representative of the former is Java,

From a file perspective, it is divided into three steps:

Written by write[]:

A.java file (you can write it with a notepad, the extension is. java),

compile[Compile]:

Compile (the cmd command is the Java a.java,ide integrated with the compiler before the run is automatically compiled) generated after the A.class file (is a bunch of binary code, people do not understand, is to see the virtual machine)

Running [Run]:

Run is the A.class file on the virtual machine running, in the console or DOS output, a typical helloworld! to complete the execution

There is a need to mention Java's "write Once, run everywhere", for example, when Windows compiles a. class file to run in a Linux environment, the root cause is the virtual machine [JVM] Only. Class two-class code files, out of the platform limitations, so there is a benefit is not to see the source code, unless the anti-compilation, copy is no place to copy.

1.2

Explanation run does not produce intermediate code, just like a translation, a sentence to execute a sentence, the scripting language is the principle of the implementation of this

A typical disadvantage of this operation is a 10-cycle for loop, it has to be translated 10 times, resulting in repeated execution of the same piece of code, so the execution efficiency is lower

But for short code, there is no amount of computation (the spooler has a certain amount of computation), the performance impact is not very obvious, which is why the scripting language is always used in the front-end some simple effects and calculations of reasons

Two person learning paths

In the school soy sauce of the Java EE project to do some front-end effects, the team leader is the front end of the whole package, I this when the younger brother looked at the team leader so hard unkind (actually also want to learn a little things), so volunteered to imitate the team leader that several pages of the script also completed some work. The original understanding is divert, not on jquery, just a few selectors, callback functions of what, what is difficult? I found a few video podcast videos to see, got into the door, began to pit Captain ... One of the most mentally retarded problems is the int i=$ ("#div1"). HTML (), then suppressed for a long time did not want to understand, so SB's problem unexpectedly put the leader in, also smarty pants debugging for half a day ... Look at yourself is not the Red Fork is unable to respond to the script, not to mention how sad. Sad to sad, the pit still have to continue the pit, in addition to the people code stick down to change to dog excrement, is in Firefox F12 change their dog excrement, wasted a lot of energy. Eat a lot of losses, or summarize it.

1. Other people's experience can not replace their own thinking. Personally speaking, at that time I was very much admire my team leader, technical first-class, problem-solving ability, perseverance, and my team leader of the character, did not stick to the technical Daniel narcissistic odor, every time my mentally retarded bug He is good patiently adjusted (if it is the people who do it may only use half the time), and is willing to put the technology But why does my script still write so bad? Because I am lazy, my mind scales tend to rely on other people's experience, want to take a shortcut. This is a foolish thought, as a technical staff, gave up the thinking and exploration of technology, just like the wolf gave up his teeth and claws, looking to eat from the mouth of other people chew meat, use into the scrap, a long time, you have to face the fate of being eliminated.

2. Do not impetuous before doing, the normal course of study should be like this: first understand the DOM model, and then write some simple JS script to get started, then the system of learning jquery (after all, the powerful, JS is the foundation, but the main is to understand the idea, back to the problem and then review JS is not too late). Recommend a website: The network, the code has a display function, fun, more vivid. Recommend a jquery tool: Webstorm, its powerful simply can be described by the lunatic, from now on mother no longer worry I will not jquery.

Three Technical summary

jquery is the library of JavaScript, the so-called library is to JS to do a package, if JS is a raw fish, then jquery is braised well in the vacuum bag in the cooked food, edible more convenient. Before the boring syntax is explained, it is necessary to speak about the DOM model.

The Document Object model is a browser-based model that abstracts the elements of the browser page into a tree structure, the root element is document, the branches are <div>, and the blocks, like the provinces in the map, have <p> below; text,< Img>, pictures, and so on, one of the great benefits of organizing is that it is organized and can be traversed to every element through a parent-child, neighbor relationship, which is easily accepted from both the computer and the human perspective. Each element wants to be selected to have four paths (sorted by common degree):

1.id selection: <p id= "P1" class= "Style1" > I was a phrase </p>; $ ("#p1") "$ for the Juqery selector, () inside is a string, so to quote, #的含义是代表id"

2. Element selection: $ ("P") "Select all paragraph elements"

3. Class Selector: $ (". Style1") "Select elements of this type Style1"

4. The selector with relative position: $ ("#p1"). Find ("P10") "selects all child elements between P1 and P10"

The browser is abstracted by the DOM model, so what happens after you get the element? Now let's talk about another feature of Jquery/js: weak type

We know that there are eight basic data types in Java, from int to char, and in order to conform to object-oriented thinking, eight basic data types are boxed: from integer to character, and then to the parent class of all objects. The object class (from which you can see that the tree structure is widely used in computer applications), but in Jquery/js, there is only one type, var type, var type, like Monkey King, contains all the variants from int to object (all types you can think of, Anyway declaring the variable up is Var,var a= ' 100 ' declares a string 100,var a=100 declares the shaping 100, the former plus 200 is 100200, the latter is 300):

For example, declare an array (two-dimensional): Var a=new array (); A[1]=new Array ("A", "B");

For example, get the tag element and change the CSS style: var p1=$ ("#p1") p1.attr ("Font-color": Red)

You can also define objects (they call it json, which is the object in the script, note that this is an employee rather than a normal abstract type):

var employees=[{"name": "BillGates", "money": "+"},{"name": "Baffete", "money": "200"}]

An array of objects has been set up, with two employees, Gates and Warren Buffett, if you want to see the gates deposit then the following code can do it:

$ ("#p1"). HTML ("<B>" +employee[0].money+ "</B>"), let P1 's content show gates deposit 100 bucks, haha

The DOM model is modeled as a browser, and the var type acts as a container for accepted objects. I came to think of MVC's design idea (model[model]+view[View]+controller[control layer], no matter from the request response process angle, It is also a perfect software design idea from the angle of decoupling extraction code. Then Dom and Var belong to the M-layer, with bricks in their hands [the basic unit of the House], and the next thing to consider is how to get the bricks organized, or to make the relationships between the bricks move.

From the customer's point of view, computer interaction by mouse, it is easy to think of the mouse two operations, click and move, corresponding to the two most commonly used events click and mouseover

$ ("button"). Click (function () {executed code}) the meaning of this code is that clicking on the button triggers a function (if the function is only used to click on the name, similar to the anonymous function), the complete code is like this, $ (document). Ready is the first piece of code that executes when the browser opens the page:

<ScriptType= > 
$ (document ). ready (function () {
$ ( "#mm"). click (function () {
alert ( "123")
})
})

</script ;

If a function is used for a lot of events, then you can do this, onclick= "a ()" is the event that is triggered when the button is clicked:

<type=>
A () {
Alert ("Nihao a")
}
</Script>

<input type="button" id="MM" onclick= "A ()">
A classic jquery code of two ways to complete this, it is to achieve the function is to click on the button to pop up a Hello Ah dialog, then you can move some small hands on this basis, such as adding a 1000-millisecond animation, click the button, let a canvas (div) Fill the entire screen, stretch, fade out, Displays the specified text and so on .... In addition to sending Ajax requests, the so-called AJAX (Asynchronous Message Processing), popularly speaking is different from the traditional TCP interaction mode "synchronous processing", a typical example of the traditional way is to send a request, callback response after the entire page, For some requests (such as simply altering a page's data), the asynchronous message processing was invented because of the large consumption of resources (recalling the synchronous and asynchronous, the popular synchronization is a shout B to eat, a only after the response of B to do other things, asynchronous a only send messages, instead of waiting for b response), A response is received without refreshing the entire page, and the data sent and received can be in a JSON-style format.

A review of four broken thoughts

This part is mainly for some scattered knowledge points to do some review, the code basically all ran once, see the effect will also have a sense of accomplishment, mainly review the bits of jquery (after understanding the thought actually to here is like remembering the word, I from the top of the list to chop down some scattered, like a dictionary to leave an index, Convenient later use when review), will also be interspersed with a little json,ajax, learning when attention to promote (such as Object-"array object; Get CSS Properties-" Get CSS Multiple properties-"Modify CSS multiple properties, dropdown-" pull-"animation time, Speed-" Can you write a callback function?)

4.1 Syntax

Introducing the jquery library in the head

Grammar:
$ (this). Hide ()
$ (selector). Action () dollar symbol for jquery, selector selector query and find HTML element, action () performs meta- action

$ (document). Ready (function () {...});
Selector: $ ("P#demo") Select all the Id=demo <p> elements $ ("[href$= '. jpg ']") to select all the href values with ". jpg" ending with the element $ ("P"). CSS ("Background-color", " Red "); Select all elements of the specified style

4.2 Effect (the effect can be added to callback as a parameter, that is, the callback function "executes after the effect of the callback function")

Hide (), Hidden, show (), display, toggle () hidden into display, show as hidden

Fadein (), Fade in (show hidden elements gradually); fadeout, fade out; Fadetoggle,fadeto ("Slow", 0.7) speed, transparency

$ ("button"). Click (function () {$ ("div"). Animate ({left: ' 250px ', Height: ' +=150px ', Width: ' +=150px '});});

Animate: Performing animations

$ ("button"). Click (function () {var div=$ ("div"); Div.animate ({left: ' 100px '}, "slow"); Div.animate ({fontSize: ' 3em '}, " Slow "); })

The above line of code performs 2 animations

Stop: Stop animation

$ ("P"). Hide (1000,function () {alert ("the paragraph is now hidden");});

Callback The Nameless function after performing the fade

$ ("#p1"). CSS ("Color", "red"). Slideup (+). Slidedown (2000);

The two-segment function was executed after changing the style

4.3 jquery and HTML

    • Text ()-Sets or returns the text content of the selected element
    • HTML ()-Sets or returns the contents of the selected element (including HTML tags)
    • Val ()-Sets or returns the value of the form field-primarily the contents of the Input box label

The contents can also be set: $ ("#p1"). HTML ("<p>" + I am a text + "</p>")

$ ("#test1"). Text (function (i,origtext) {
Return "Old text:" + origtext + "New Text:hello world! (Index: "+ i +") ";

Get the old text and display it in the callback function

attr Property

$ ("button"). Click (function () {  $ ("#w3s"). attr ("href", function (i,origvalue) {    return origvalue + "/jquery";  }); })
Change the content of a link

4.4 Add
    • Append ()-inserts content at the end of the selected element
    • Prepend ()-Inserts content at the beginning of the selected element
    • After ()-Inserts the content after the selected element
    • Before ()-insert content before selected element
$ ("P"). Prepend ("Some prepended text.");

4.5 Delete
    • Remove ()-Deletes the selected element (and its child elements)
    • Empty ()-Removes child elements from the selected element
$ ("P"). Remove (". Italic");
The above example removes all <p> elements of the class= "italic":

4.6jquery and CSS
Example:
. Important{font-weight:bold;font-size:xx-large;}
$ ("div"). AddClass ("important");
    • AddClass ()-adds one or more classes to the selected element
    • Removeclass ()-deletes one or more classes from the selected element
    • Toggleclass ()-switch operation to add/Remove classes for selected elements
    • CSS ()-Set or return style properties

A new style for P is set

$ ("P"). css ({"Background-color": "Yellow", "font-size": "200%"});
Size
    • Width ()
    • Height ()

$ ("#div1"). Width () returns the thickness of the canvas

4.7jquery traversal

Dom is like a family, and through the veins you can find every member

An upward parent,parents,parentsuntil ("mm") between the elements

The Children,children ("p.1") class of 1 is the P element, where find ("span") is between

    • Siblings ()
    • Next ()
    • Nextall ()
    • Nextuntil ()
    • Prev ()
    • Prevall ()
    • Prevuntil ()

All compatriots, next compatriots, next all compatriots, to a certain element of all compatriots

First,last,eq,filter (". Intro"), not five filters, it seems that they are first selected to the element and then filtered

$ ("P"). Not (". Intro"); P element that is not a intro class

4.8 AJAX
$ ("button"). Click (function () {  $ ("#div1"). Load ("Demo_test.txt", function (RESPONSETXT,STATUSTXT,XHR) {    if ( statustxt== "Success")      alert ("External content loaded successfully!") ");    if (statustxt== "error")      alert ("Error:" +xhr.status+ ":" +xhr.statustext);  });
Let Div1 load the contents of Demo_test, callback is a format, XHR encapsulated response header, success, return 200 and Success,statustxt is the true return value

$ ("button"). Click (function () {  $.post ("demo_test_post.asp",  {    name: "Donald Duck", City    : "Duckburg "  },  function (data,status) {    alert (" Data: "+ Data +" \nstatus: "+ status);  });
Key points: url (like who requests, where to go?), data (in the form of Key-value), feedback (information, status [success]? Failed])


<%dim fname,cityfname=request.form ("name") City=request.form ("City") Response.Write ("Dear" & fname & ".") Response.Write ("Hope you live ' Well ' & City &". ") %>
Interactive code, take things, handle, return

Noconflic as a conflict when dealing with the $ expression symbol as other framework keywords, very rarely, to use when the Baidu Bar

Java Scripting language learning experience

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.