现状:
在 2016 年学 JavaScript 是一种什么样的体验?
新特性:
ECMAScript 6 — New Features: Overview & Comparison
框架:
趋势:
All these functions are used to attach an event handler function to the selected elements or selectors. In this article I will take you through all the four set of functions to get an idea of what it is.
To start with, let me list down all the functions with short description and release details.
Method | Short Description | Added In | Deprecated In | Removed In |
.bind() | Attach a handler to an event for the elements. | 1.0 | ||
.unbind() |
Remove a previously-attached event handler from the elements.
|
1.0 | ||
.live() | Attach an event handler for all elements which match the current selector, now and in the future. | 1.3 | 1.7 | 1.9 |
.die() | Remove event handlers previously attached using .live() from the elements. | 1.3 | 1.7 | 1.9 |
.delegate() | Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements. | 1.4.2 | ||
.undelegate() |
Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements.
|
1.4.2 | ||
.on() |
Attach an event handler function for one or more events to the selected elements.
|
1.7 | ||
.off() | Remove an event handler. | 1.7 |
Which function to use? confused let’s go through the below details then you will be in a good position to decide which one to use and when.
The .bind()
method is used to register an events to existing html elements and .unbind()
method is used to remove events, that are registered by .bind() method.
Syntax:-
Method | Syntax | Available from version |
.bind() | .bind( eventType [, eventData ], handler(eventObject) ) | 1.0 |
.bind( eventType [, eventData ], preventBubble )
|
1.4.3 | |
.bind( events ) | 1.4 | |
Parameter details are given below,
|
||
.unbind() | .unbind( [eventType ] [, handler(eventObject) ] ) | 1.0 |
.unbind( eventType, false ) | 1.4.3 | |
.unbind( event )
|
1.4 | |
Parameter details are given below,
|
Sample : –
$( document ).ready(function() {
$( "#foo" ).bind( "click", function( event ) {
alert( "The mouse cursor is at (" +
event.pageX + ", " + event.pageY +
")" );
});
});
The above code will cause a click on the element with ID foo to report the page coordinates of the mouse cursor at the time of the click.
Read more from http://api.jquery.com/bind/, http://api.jquery.com/unbind/
.live()
method is used to add event handler to elements that are currently available in the page or dynamically added to the page whereas .die()
is used to remove any handler that has been attached with .live()
.
Note: .live()
and .die()
are removed from jQuery version 1.9.
Method | Syntax | Available from version |
.live() | .live( events, handler(eventObject) ) | 1.3 |
.live( events, data, handler(eventObject) )
|
1.4 | |
.live( events ) | 1.4.3 | |
Parameter details are given below,
|
||
.die() | .die( eventType [, handler ] ) | 1.3 |
.die() | 1.4.1 | |
.die( events )
|
1.4.3 | |
Parameter details are given below,
|
Sample:-
<a class="link">Link Static</a>
<button id="addmore" type="button">Add more</button>
$(document).ready(function() {
$('#addmore').click(function() {
$('body').append(' <a class="link">Link Dynamic</a>');
return false;
});
$("a.link").bind('click', function() {
alert('I am clicked');
});
});
As per the above code, when ever we click on the hyper-link (<a>) it will show an alert message.. We can add hyper-links dynamically using the button. but dynamically added links will not have click event attached. To make it work for both static control and dynamic we need to rewrite the code using live() as below,
<a class="link">Link Static</a>
<button id="addmore" type="button">Add more</button>
$(document).ready(function() {
$('#addmore').click(function() {
$('body').append(' <a class="link">Link Dynamic</a>');
return false;
});
$("a.link").live('click', function() {
alert('I am clicked');
});
});
Now all the static and dynamically created links will have the alert method event attached.
Read more from http://api.jquery.com/live/, http://api.jquery.com/die/
.delegate()
method behaves in a similar fashion to the .live()
method, but the major difference is that It attaches the event handler to the context , rather than the document. The .undelegate()
method is a way of removing event handlers that have been bound using .delegate()
.
Method | Syntax | Available from version |
.delegate() | .delegate( selector, eventType, handler(eventObject) ) | 1.4.2 |
.delegate( selector, eventType, eventData, handler(eventObject) )
|
1.4.2 | |
.delegate( selector, events ) | 1.4.3 | |
Parameter details are given below,
|
||
.undelegate() | .undelegate() | 1.4.2 |
.undelegate( selector, eventType ) | 1.4.2 | |
.undelegate( selector, eventType, handler(eventObject) )
|
1.4.2 | |
.undelegate( selector, events ) | 1.4.3 | |
.undelegate( namespace ) | 1.6 | |
Parameter details are given below,
|
Sample :-
$( "table" ).delegate( "td", "click", function() {
$( this ).toggleClass( "chosen" );
});
Read more from http://api.jquery.com/delegate/, http://api.jquery.com/undelegate/
The .on()
method attaches event handlers to the currently selected set of elements in the jQuery object. The .on() method provides all functionality required for attaching event handlers. The .off()
method removes event handlers that were attached with .on()
.
Method | Syntax | Available from version |
.on() | .delegate( selector, eventType, handler(eventObject) ) | 1.4.2 |
.delegate( selector, eventType, eventData, handler(eventObject) )
|
1.4.2 | |
.delegate( selector, events ) | 1.4.3 | |
Parameter details are given below,
|
||
.off() | .off( events [, selector ] [, handler(eventObject) ] ) | 1.7 |
.off( events [, selector ] ) | 1.7 | |
Parameter details are given below,
|
Sample:-
$("p").on("click",function(){
alert("The paragraph was clicked.");
});
The above code will be attaching the specified event to all (current and future) <p>
.
Below code block is taken from jQuery 1.7.1.
You can see that for all the above listed methods the .on()
method is being “overloaded” with different signatures, which in turn changes how the event binding is wired-up. The .on()
method bring a lot of consistency to the API and hopefully makes things slightly less confusing.
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
live: function( types, data, fn ) {
jQuery( this.context ).on( types, this.selector, data, fn );
return this;
},
die: function( types, fn ) {
jQuery( this.context ).off( types, this.selector || "**", fn );
return this;
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
return arguments.length == 1 ?
this.off( selector, "**" ) :
this.off( types, selector, fn );
},
// ... more code ...
Read more from http://api.jquery.com/on/, http://api.jquery.com/off/
The .bind()
method registers the type of event and an event handler directly to the DOM element. The .bind()
doesn’t work for elements added dynamically that matches the same selector. This method is pretty easy and quick to wire-up event handlers. The shorthand methods like .click()
, .hover()
, etc make it even easier to wire-up event handlers. There is a performance issue while working with large selection as the method attaches the same event handler to every matched element in the selection.The attachment is done upfront which can have performance issues on page load.
The basic difference between .bind()
and .live()
is bind will not attach the event handler to those elements which are added/appended after DOM is loaded and there is only one event handler registered instead of the numerous event handlers that could have been registered with the .bind()
method. When using .live()
events always delegate all the way up to the document. This can affect performance if your DOM tree is deep. Chaining is not properly supported using .live()
method. Using event.stopPropagation()
is no longer helpful because the event has already delegated all the way up to the document. .live()
method is deprecated as of jQuery 1.7 and removed from jQuery 1.9.
The .delegate()
method is very powerful, The difference between .live()
and .delegate()
is, live function can’t be used in chaining. live function needs to be used directly on a selector/element. Also .delegate()
works on dynamically added elements to the DOM where the selectors match. Chaining is supported correctly in .delegate()
.
The .on()
method attaches event handlers to the currently selected set of elements in the jQuery object. As of jQuery 1.7, the .on()
method provides all functionality required for attaching event handlers. Brings uniformity to the various event binding methods. but as the the way we call .on()
method the behaviour also changes.
Note: If you are using jQuery 1.7+ then its advised to use .on()
for attaching events to elements or selectors.
Conclusion
All the these jQuery functions are used to attach events to selectors or elements. Some methods performs better in some situations. If you are using jQuery 1.7+ then its advised to use .on()
over all the event binding methods.
In this article I have given detailed explanation of jQuery methods that’s used for attaching/removing event handlers. I hope you have enjoyed this article and got some value addition to your knowledge.
from: http://www.codeproject.com/Articles/778374/JQUERY-JSON-and-Angular-Interview-questions
So will jquery replace javascript ?
So how do we use these reusable jquery libraries?
What is CDN (Content delivery network)?
For Jquery files which are the popular CDN’s?
How can we reference local Jquery files if CDN fails?
What is the difference between Jquery.js and Jquery.min.js file?
When should we use jquery.js over jquery.min.js ?
What is the use jquery.vsdoc.js ?
How does the basic syntax of Jquery looks like?
What is the “$” sign in Jquery ?
WhenshouldweuseJquery.noConflict()
What are the different ways by which you can select a HTML element in JQuery ?
What is the use of Document.ready in Jquery ?
Can we have two document.ready in a webpage?
Do all technologies support JSON?
How can you make a JSON call using Jquery ?
How can we post JSON to Server?
How can we post a complete HTML form in JSON format?
How can we convert JSON string in to c# object?
What are single page applications (SPA)?
What is the need of ng-model, ng-expression and ng-app in Angular?
How is the data binding in Angular?
Jquery is a reusable javascript library which simplifies javascript coding. So rather than writing length javascript code as below.
document.getElementById("txt1").value = "hello";
By jquery the above javascript code is now simplified as below.
$("#txt1").val("Hello");
If you want to kick start with Jquery start with the below video which is created by www.questpond.com
No, Jquery is not meant to replace javascript. Jquery is a library while javascript is a language. Jquery sits on the top of javascript to make your development easy.
You need to download Jquery.js file from jquery.com and include the same in your web pages. The jquery files are named with version number like “jquery-1.4.1.js” where 1.4.1 is the version of the JS file. So at the top of your web page you need to include the javascript as shown in the below code.
<script src="file:///C:/Documents%20and%20Settings/admin/Documents/My%20Web%20Sites/Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
In CDN multiple copies of the website is copied on different geographical servers. When users request website content which have CDN enabled depending on their geographical location , content is served from the nearest geographical location server of the user.
So if a user is from India, the Indian CDN server will serve request for Indian users. This leads to faster delivery of data.
There are two popular CDN’s Microsoft and google.
If you want to reference google CDN Jquery files you can use the below script.
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
If you want to use Microsoft CDN you can use the below javascript.
<script type="text/javascript"
src="http://ajax.microsoft.com/ajax/jquery/jquery-1.9.1.min.js">
</script>
Many times it’s possible that Microsoft and google servers can go down for some time. So in those situations you would like your page to reference jquery files from local server.
So to implement a CDN fallback is a two-step process:-
First reference the CDN jquery. In the below code you can see we have reference Microsoft CDN jquery file.
http://ajax.microsoft.com/ajax/jquery/jquery-1.9.1.min.js "></script>
Now if Microsoft CDN is down then the Jquery value will be “undefined”. So you can see in the below code we are checking if the Jquery is having “undefined” value then do a document write and reference your local Jquery files.
if (typeof jQuery == 'undefined')
{
document.write(unescape("%3Cscript src='Scripts/jquery.1.9.1.min.js' type='text/javascript'%3E%3C/script%3E"));
}
Below is the full code for the same.
<script type="text/javascript" src="file:///C:/Documents%20and%20Settings/admin/Documents/My%20Web%20Sites/%20http:/ajax.microsoft.com/ajax/jquery/jquery-1.9.1.min.js%2520"></script>
<script type="text/javascript">
if (typeof jQuery == 'undefined')
{
document.write(unescape("%3Cscript src='Scripts/jquery.1.9.1.min.js' type='text/javascript'%3E%3C/script%3E"));
}
</script>
First thing both the files provide the same jquery functionalities. One is a long version and the other is compressed / minified version. The minified version is compressed to save bandwidth and space by compressing and removing all the white spaces.
Below is the view of Jquery.js.
Below this is view of Jquery.min.js file (compressed and minified).
When you are doing development use “jquery.js” file because you would like to debug, see the javascript code etc. Use “Jquery.min.js” for production environment. In production / live environment we would like to consume less bandwidth, we would like to our pages to load faster.
This file you can include if you want to enable intellisense in visual studio for Jquery.
Jquery syntax structure can be broken down in to four parts:-
The “$” sign is an alias for jquery.
There are many javascript frameworks like MooTools, Backbone, Sammy, Cappuccino, Knockout etc. Some of these frameworks also use “$” sign so this can lead to conflict with Jquery framework.
So you can use the “noConflict” method and release the jquery “$” sign as shown in the below code.
$.noConflict();
jQuery("p").text("I am jquery and I am working…");
You can also create your own jquery shortcut as shown below.
var jq = $.noConflict();
jq("p").text("I am invoked using jquery shortcut…");
You can select Jquery elements in the following ways:-
Select all
Below is a simple code snippet which selects all paragraph tags and hides them.
$("p").hide();
Select by ID
$("#Text1").val("Shiv");
Select using Equal method
Select using Find method
Select using Filter method
“Document.Ready” event occurs once the complete HTML DOM is loaded. So the next question is when do we actually need this event?. Consider the below simple code where we are trying to set a text box “text1” with value “Sometext”.
Now at the point when Jquery code tries set the textbox value , at that moment that text box is not available in the HTML DOM. So it throws an exception for the same.
<script>
$("#text1").val("Sometext"); // Throws exception as the textbox is not //accessible at this moment
</script>
</head>
<body>
<input type="text" id="text1" />
</body>
So we would like to execute the Jquery code which sets the textbox value only when all the HTML objects are loaded in DOM. So you can replace the code of setting text box value to something as shown below.
<script>
$(document).ready(function(){
$("#text1").val("Sometext");
});
</script>
Here is a nice detail article with a video which explains Jquery Ready event in a more detail manner http://www.dotnetinterviewquestions.in/article_jquery-interview-questions:-when-do-we-need-documentreadyevent-_230.html
Yes.
Below is a simple code which attaches a function to click event of a button.
$("button").click(function(){
$("p").toggle();
});
Below is one more example where we have attached the a function to a mouse enter event of a paragraph.
$("#p1").mouseenter(function(){
alert("You entered p1!");
});
$(“li”).filter(“.middle”).addClass(“selected”);
<style>
.selected { color:red; }
</style>
JSON (JavaScript object notation) helps us to present and exchange data in a self-descriptive, independent and light way. This data can then be easily consumed and transformed in to javascript objects.
Below is a simple example of JSON format looks. You can understand from the format how lightweight and easy the format looks.
Figure :- JSON
The biggest advantage of JSON format is it can be evaluated to a javascript object. For instance you can see in the below code snippet we have a JSON format data which has “name”,”street”,”age” and “phone”. Now this data can be consumed as shown in the code snippet below, evaluated to a javascript object and invoked as anobject property.
You can see how we have called the “name” property using an object “JSONObject.name”.
<script type="text/javascript">
var JSONObject= {
"name":"John Johnson",
"street":"Oslo West 555",
"age":33,
"phone":"555 1234567"};
alert(JSONObject.name);
</script>
SOAP is heavy due to XML tags. For example a SOAP message “Shiv” will become short , sweet and light in JSON like “Name” : “Shiv”. Second most important it evaluates as javascript object. To convert the complicated SOAP XML in to javascript JSON object would be a tough and tedious task.
Figure 11.11:- SOAP meant to do the same thing
Yes , Almost all technologies who deal with exchange of data support JSON. For instance if you want to that your WCF service should send JSON message rather than SOAP you can set the “ResponseFormat” as “WebMessageFormat.Json” on your operation contract.
[OperationContract]
[WebInvoke(Method="GET", UriTemplate="/GetData", RequestFormat=WebMessageFormat.Json,
ResponseFormat=WebMessageFormat.Json)]
string GetData();
If you want your MVC to emit out JSON data you can return “JsonResult” as shown below. If you call the below action it will emit out Customer objects in Json format.
public JsonResult CustomerJson()
{
List<Customer> obj1 = new List<Customer>();
Thread.Sleep(5000);
Customer obj = new Customer();
obj.CustomerCode = "1001";
obj1.Add(obj);
return Json(obj1,JsonRequestBehavior.AllowGet);
}
If you want to emit JSON using ASP.NET we need to use the “DataContractJsonSerializer” class as shown in the below code.”myPerson” is the class.
DataContractJsonSerializer serializer = new DataContractJsonSerializer(myPerson.GetType());
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, myPerson);
string json = System.Text.Encoding.UTF8.GetString(ms.ToArray());
Response.Clear();
Response.ContentType = "application/json;charset=utf-8";
Response.Write(json);
Response.End();
Let’s assume you have a MVC controller action “getEmployee” which emits out employee JSON object as shown in the below code. Please note you can always emit JSON from any server technology like WCF , ASP.NET , MVC etc as discussed in the previous questions.
public JsonResult getEmployee()
{
Emp obj = new Emp();
obj.empcode = "1001";
return Json(obj,JsonRequestBehavior.AllowGet);
}
To make a call to the above MVC action using Jquery we need to use “getJSON” method. Below is the simple code for the same. It has three parameters:-
$.getJSON("/Employee/getEmployee", null, getData);
function getData(data)
{
alert(data.empcode);
}
We can use the “post” method of jquery to send data to the server. Below is how the post method call looks like. First parameter is the URL which will accept JSON data, second is the data which we want to send and the final parameter is the call back function where we receive the response.
var mydata ={name:"Shiv",city:"Mumbai"};
$.post("/Send/Request", // URL
mydata , // Data to be sent
function(data,status){alert(data + “ “ + status);}); // Call back function
To post a complete HTML form we need to call “serialize” function as shown in the below code. “form1” is a HTML form. The data given by the function can then be passed to the “post” method of Jquery.”DisplayData” is a callback function to handle the output given by the server.
var Mydata = $("#form1").serialize();
$.post("/Customer/getCustomer",JSON. stringify (MyData), DisplayData);
The above posted JSON string is received at the server side “request.inputstream” , below is a simple sample code for the same.
System.IO.Stream body = Request.InputStream;
System.IO.StreamReader reader = new System.IO.StreamReader(body);
string s = reader.ReadToEnd() ;
To convert a JSON string to a c# object we need to use the “JavascriptSerializer” class as shown in the below code.
“JsonString” is the string which has the JSON value and by using “Deserialize” we are converting the string to a c# object. Now this object which we receive is a collection of “key” and “value” pair which can be browsed and accessed in c#.
var jsonser = new JavaScriptSerializer()
var obj = jsonser.Deserialize<dynamic>(JsonString);
foreach (var x in obj)
{
String strvalue = x[“value”];
}
SPA means you web page has the following :-
Angular JS is JavaScript framework to create SPA applications. It simplifies complex javascript DOM manipulation code by providing declarative tags. This provides a clean separation between DOM manipulation logic and the HTML view.
For example below is a simple Angular code which helps us to display textbox data in the DIV tag when the user types in the textbox.
<input type=text ng-model="name">
<div>
Current user's name: {{name}}
Below is a simple video which explain Angular in 5 minutes with an example: –
“ng-model” helps to store data which is typed in the HTML elements while expression helps to display the model data on the page. “ng-app” defines the root element for angular.
Below is a simple angular code which has all the three things: –
<div ng-app>
<input type=text ng-model="name">
Current user's name: {{name}}
</div>
Its two way binding. So whenever you make changes in one entity the other entity also gets updated.
from: http://www.codeproject.com/Articles/778374/JQUERY-JSON-and-Angular-Interview-questions