jquery Plug-in-jrating scoring plug-in source code analysis and the use of methods _jquery

Source: Internet
Author: User
Tags extend one table set background vars
The plug-in is widely used in a variety of needs to score the page, today as a learning, the source code out analysis, by the way to learn its use.
first, the use of plug-ins at a glance
Copy Code code as follows:

<div>
<div> First example </div>
<div id= "16_1" class= "myrating" ></div>
</div>

Copy Code code as follows:

<link href= "Script/jrating/jrating.jquery.css" rel= "stylesheet" type= "Text/css"/>
<script src= "Script/jquery-1.7.min.js" type= "Text/javascript" ></script>
<script src= "Script/jrating/jrating.jquery.js" type= "Text/javascript" ></script>
<script type= "Text/javascript" >
$ (function () {
$ (". Myrating"). Jrating ({
Length:10
});
});
</script>

Execution Effect

As you can see, in the example above, there are 10 stars, which are the function of length of the parameter. Among them, the default total score is 20 points, is 10 stars are selected. Here we focus on <div> Id16_1, where 16 is used to initialize the rating plugin default selection ratio, 16/20 * 10. So there are 8 stars above us that are yellow.

When we put the mouse on the plugin, the small star will increase or decrease as the mouse moves (red will cover yellow or white), the score is from 0 to 20, but when you click the mouse, the score is over, the plugin can no longer be edited, and, through Ajax, post data to the specified path, and then use the background data to persist the scoring data.

Before we analyze the source code, let's take a look at the optional parameters for using the plug-in:

Second, the plug-in source code analysis

According to the recommendation of the jquery plugin, the following techniques are used at the beginning of the source code to avoid conflicts between the shortcut symbol "$" and other JavaScript plug-ins:
Copy Code code as follows:

(function ($) {
$.fn.jrating = function (OP) {
Here is the plug-in code
}
}) (Jqurery)

Next, all the code that we analyze will appear in the green section above, setting the default parameters first.
Copy Code code as follows:

var defaults = {
/** String VARs **/
Bigstarspath: ' Icons/stars.png ',//setting the relative path of the big Star (default display)
Smallstarspath: ' Icons/small.png ',//Little Star
Phppath: ' php/jrating.php ',//click mouse, score OK, post data address, next we will use ASP.net technology for processing
Type: ' big ',//You can see that the default is to use the large star
/** Boolean VARs **/
Step:false,//If set to True, the stars are either completely discolored or not all changed, of course, this also applies to the selection of fractions is synchronized.
Isdisabled:false,//If set to True, the plugin cannot be edited, and the default is true when the mouse is clicked
Showrateinfo:true,////When the mouse is placed on the star, display the selection ratio information below the mouse, for example 16/20
/** Integer VARs **/
Length:5,//number of stars
decimallength:0,///Selected number of decimal places, up to 3 digits, if set to 1, may occur for 16.3/20
RATEMAX:20,//proportions in the denominator, integer 0-9999
RATEINFOSX:-45,//Information cue box position relative to the position of the mouse
Rateinfosy:5,//ibid., ordinate position
/** functions **/
Onsuccess:null,//Successful callback function
Onerror:null//Error handling function
};

Through the green section above, we can see the default values of all parameters, and we can use in plug-ins, according to the requirements to determine the appropriate configuration, the use of plug-ins is not the combination of these parameters?
Next we'll look at a function scope:
Copy Code code as follows:

if (this.length>0)
Return This.each (function () {//The next occurrence of the code, will be here!!! }

This code is very simple, we're going to execute the jrating () function on the selected collection, which first determines whether the collection is longer than 0, and if 1 or more, executes each () function on the collection, dealing with each element (Div) in the collection separately.
The core code of the plug-in is actually in the each () function above, we look at several functions, which are defined in each () function and called by other statements.
Copy Code code as follows:

function Findrealleft (obj) {
if (!obj) return 0;
return obj.offsetleft + findrealleft (obj.offsetparent);
};

Focus first on the Findrealleft () function, which receives an object parameter named obj, and finally returns the distance of the element object relative to the left edge of the browser. Note: offsetparent refers to the element's closest location (Relative,absolute) ancestor element, which points to the BODY element if no ancestor element is positioned. Offsetleft returns the position relative to the offsetparent.
Copy Code code as follows:

function Getnote (Relativex) {
var Notebrut = parsefloat ((relativex*100/widthratingcontainer) *opts.ratemax/100); Whether two 100 can be removed, indicating the proportion of choices, such as 16 or 16.1
Switch (opts.decimallength) {///To determine the number of decimal places required to be lost by parameter, for example 16.1 16.12 16.123
Case 1:
var note = Math.Round (notebrut*10)/10;
Break
Case 2:
var note = Math.Round (notebrut*100)/100;
Break
Case 3:
var note = Math.Round (notebrut*1000)/1000;
Break
Default:
var note = Math.Round (notebrut*1)/1;
}
return note;
};

Then pay attention to the Getnote function, first we look at the following Relativex is a thing:
Copy Code code as follows:

var realoffsetleft = Findrealleft (this);
var Relativex = E.pagex-realoffsetleft;

The above two lines of code are used to define Relativex variables before calling the Getnote function, we can analyze the function of Relativex. Here is a div where we apply the jrating () function to get its left margin relative to the browser, because the above two lines of code appear in the mouse movement handler MouseEnter (which we'll see later). So the E.pagex here represents the horizontal distance of the mouse relative to the browser. Therefore, the relativex here represents the lateral distance of the mouse relative to the <div> left boundary.
We pay attention again to the Getnote function, by Widthratingcontainer = Starwidth*opts.length can be seen, Widthratingcontainer is the left and right star picture added width. Therefore, var Notebrut = parsefloat ((relativex*100/widthratingcontainer) *opts.ratemax/100) can be removed by the denominator and two 100 of the molecule, i.e. (Relativex /widthratingcontainer) *opts.ratemax, the Notebrut variable last stores the proportion of the mouse selection, and if the Ratemax is set to 20, the Notebrut range can be determined by the mouse (0-20).
The switch function, which determines the number of digits that are displayed (proportionally), through the decimallength parameter (the decimal bit used to set the zoom). Read here, we can find that the Getnote function is the RELATIVX to return the mouse to select the proportion of what this ratio is, see the following figure with the Brush box part:

Next, we'll focus on a function
Copy Code code as follows:

function Getstarwidth () {
Switch (opts.type) {
Case ' small ':
Starwidth = 12; Small.png the width of the small star picture
Starheight = 10; Height
Bgpath = Opts.smallstarspath; Picture relative address
Break
Default:
Starwidth = 23; The width of the large star can be seen, which is the default value
Starheight = 20; Height
Bgpath = Opts.bigstarspath; Star Picture Relative address
}
};

This is a relatively simple function for initializing variables, according to the type attribute, initialize three variables, respectively, Starwidth, Starheight, Bgpath, green annotation information has been able to explain everything, no longer repeat!
The functions defined in each () are read, and then we wander through the each () function, and we intercept a few lines of code, from top to bottom, as follows:
Copy Code code as follows:

var opts = $.extend (defaults, OP),///Use the Extend () function to merge the default parameters with the input parameters and finally store them in the OPTs variable.
Newwidth = 0,//defines a variable that is used to store Relativex, but adjusts accordingly according to the Step property
Starwidth = 0,//define variable, width of the star
Starheight = 0,//height
Bgpath = '; Star Image Address
if ($ (this). Hasclass (' jdisabled ') | | | opts.isdisabled)//Determine the jdisabled variable to indicate whether the div can be manipulated
var jdisabled = true;
Else
var jdisabled = false;
Getstarwidth (); This function does not repeat, the above analysis
$ (this). Height (starheight); Determine the height of this div according to the height of the star.

then look down .
Copy Code code as follows:

var average = parsefloat ($ (this). attr (' id '). Split ('_') [0]),//<div> ID (for example, 16_2), get the number in front of the underscore, and use the number as the default selection ratio
Idbox = parseint ($ (this). attr (' id '). Split ('_') [1]),//underline the following section as the ID of the identification scoring plug-in
Widthratingcontainer = Starwidth*opts.length,//Star picture width sum, and as peripheral container width
Widthcolor = Average/opts.ratemax*widthratingcontainer,//color block occupied width

Next, we'll see the new three <div&gt, and insert into the main div
Copy Code code as follows:

quotient =
$ (' <div> ',
{
' Class ': ' Jratingcolor ',
css:{
Width:widthcolor
}
}). Appendto ($ (this)),
Average =
$ (' <div> ',
{
' Class ': ' Jratingaverage ',
css:{
width:0,
top:-Starheight
}
}). Appendto ($ (this)),
Jstar =
$ (' <div> ',
{
' Class ': ' Jstar ',
css:{
Width:widthratingcontainer,
Height:starheight,
top:-(starheight*2),
Background: ' url (' +bgpath+ ') repeat-x '
}
}). Appendto ($ (this));

First we analyze the first <div&gt, its class name is Jratingcolor, it represents the default proportions, in yellow, its length is withcolor, here is the main look at its style sheet:
Copy Code code as follows:

. jratingcolor {
Background-color: #f4c239; /* bgcolor of the stars*/
position:relative; Relative positioning
top:0;
left:0;
Z-index:2; Notice here that the z-index of this div's ancestor, our each function, is 1, as we'll see immediately below.
height:100%;
}

The second <div> style sheet is as follows:
Copy Code code as follows:

. jratingaverage {
Background-color: #f62929; Red
position:relative;
top:0;
left:0;
Z-index:2;
height:100%;
}

But in the above program, when initializing, the width is set to 0 (because the mouse has not yet chosen), while changing the top value:-Star height, so it and the above div added to the vertical direction of the overlap.
Next look at the third <div&gt, mainly for the small stars.
Copy Code code as follows:

/** Div containing the stars **/
. Jstar {
position:relative;
left:0;
Z-index:3;
}

This style sheet is relatively simple, we focus on the dynamic addition of JS in the values of several properties:
Copy Code code as follows:

Width:widthratingcontainer,//Set width
Height:starheight,//height
top:-(starheight*2),//change the longitudinal direction of the value, and the top two <div> overlap
Background: ' url (' +bgpath+ ') repeat-x '//Set background for small stars

The value of the property is set, but some people may ask, what only see the small stars color is color, and the top of the above added two <div> is not a high rectangular color bar? Let's take a look at the pictures of the small stars to understand why!

Needless to say, the next with an opaque background, the middle of the small stars are transparent, the following natural color shows!!
The next statement is very simple, is to set the outermost div container style, note the Z-index property:
Copy Code code as follows:

$ (this). CSS ({width:widthratingcontainer,overflow: ' Hidden ', zindex:1,position: ' relative '});

The next step is to move into a relatively complex section where we will focus on the mouse action and its response, focusing first on a small logic:
if (!jdisabled)
The next code
As you can see, the jdisable variable we set up here is used here, and if jdisabled is true, the plugin is disabled, then the next mouse operation will not be performed.
Next look at how the mouse action is added to the plug-in:
$ (this). Unbind (). Bind ({//mouse event handling code, discussed separately below).
});
First look at the mouse to enter the event handling code
Copy Code code as follows:

Mouseenter:function (e) {
var realoffsetleft = Findrealleft (this);
var Relativex = E.pagex-realoffsetleft; First the Relativex is computed, which represents the lateral distance of the mouse relative to the outer <div> left edge
if (opts.showrateinfo)
var tooltip =
$ (' <p> ', {
' Class ': ' Jratinginfos ',
Html:getnote (Relativex) + ' <span class= maxrate ' >/' +opts.ratemax+ ' </span> ',/note here the Getnote method, The use of it has already been spoken before.
CSS: {
Top: (E.pagey + opts.rateinfosy),
Left: (E.pagex + opts.rateinfosx)
}
}). Appendto (' body '). Show ();
},

The Relativex variable is not much explained, and here's the comment and the previous mention, next, to determine if the Showrateinfo argument is true, and if true, to show scaling information (such as 16/20 below the mouse), the tooltip variable is this information box, Finally, the Appendto method is added to the body. Code logic is very simple, this function is mainly used to display the cue box <p&gt, we can focus on the <p> node style, it is absolutely positioned, and the use of code to change the top and left values, look at the relevant style sheet:
Copy Code code as follows:

P.jratinginfos {
Position:absolute;
z-index:9999;
Background:transparent url (' http://www.cnblogs.com/icons/bg_jRatingInfos.png ') no-repeat;
Color: #FFF;
Display:none;
width:91px;
height:29px;
font-size:16px;
Text-align:center;
padding-top:5px;
}
P.jratinginfos Span.maxrate {
Color: #c9c9c9;
font-size:14px;
}

Next we look at the handler function for the MouseMove event after the mouse comes in:
Copy Code code as follows:

Mousemove:function (e) {
var realoffsetleft = Findrealleft (this);
var Relativex = E.pagex-realoffsetleft;
if (opts.step) newwidth = Math.floor (relativex/starwidth) *starwidth + starwidth;
else newwidth = Relativex;
Average.width (Newwidth);
if (opts.showrateinfo)
$ ("P.jratinginfos")
. css ({
Left: (E.pagex + opts.rateinfosx)
})
. HTML (Getnote (newwidth) + ' <span class= ' maxrate ' >/' +opts.ratemax+ ' </span> ');
},

This function is mainly used to determine the proportion of mouse selection, of course, this ratio is obtained by getnote (newwidth), then determine the appropriate Newwidth value is the core of this function, If Opts.step is true, that is, the scale can only be a whole number of stars (not 15.3, and so on), then we look at this logic: Math.floor (relativex/starwidth), Starwidth is the width of the star picture, Math.floor ( -0.1) =-1,math.floor (0.1) = 0,math.floor (2.6) = 2, knowing these, the red code on top is easy to understand.
Ok,let ' s go on, look at three simple handler functions
Copy Code code as follows:

Mouseover:function (e) {
$ (this). CSS (' cursor ', ' pointer ');
},
Mouseout:function () {
$ (this). CSS (' cursor ', ' default ');
Average.width (0);
},
Mouseleave:function () {
$ ("P.jratinginfos"). Remove ();
},

The MouseOver function ensures that the mouse enters the plug-in's display style, Mouseout is the same, but it changes the div (red) width of the class name average to the 0,mouseleave function to let the message box disappear.
The last function, is also the end of the entire source, of course, the most important and most complex-mouse click function:
Copy Code code as follows:

Click:function (e) {
The next code is here.
}

Our division to come, first look at the first part:
Copy Code code as follows:

$ (this). Unbind (). CSS (' cursor ', ' Default '). AddClass (' jdisabled ');

Why here only a statement, because it is very important, but also very simple, we must pay attention to the Unbind () function, it is very important, when the mouse click, first of all other binding to the outer <div> of the event are removed, so the mouse click on the moment, The plug-in's appearance is fixed in the browser and no longer changes with mouse events. Of course, finally <div> add the jdisabled attribute.
We went back to the next step:
Copy Code code as follows:

if (opts.showrateinfo) $ ("P.jratinginfos"). Fadeout (' Fast ', function () {$ (this). Remove ();});
E.preventdefault ();
var rate = Getnote (newwidth); Focus on the rate variable, which you need to use later.
Average.width (Newwidth);

The first sentence is not difficult to understand, delete the message box, the second sentence to cancel the default operation of the mouse click, the following two sentences is very simple, no longer repeat, to know Newwidth in the previous mentioned, indicating the width of the mouse selection.
The last statement that sends the selected proportions to the server side for persistence:
Copy Code code as follows:

$.post (
Opts.phppath,//using AJAX technology to send data to the server address
{//post past Data
Idbox:idbox,
Rate:rate,
Action: ' Rating '
},
function (data) {//callback functions, which mainly pass parameters to the plug-in custom function and execute.
if (!data.error)
{
if (opts.onsuccess) opts.onsuccess (element, rate);
}
Else
{
if (opts.onerror) opts.onerror (element, rate);
}
},
' JSON '//determine how to interpret the returned data, which uses JSON.
);

Using jquery to do Ajax is really simple, the code to do the necessary comments, here no longer repeat, the source code of the plugin is analyzed, relatively coarse, but the whole logic may reflect some, hope that the study notes for everyone can help. Here we go to the actual combat phase.
third, the actual combat jrating plug-in
In order to get closer to the real application, we first use SQL Server to build a database table, which is an article type table, with ID, title, article content, rating four fields, screenshots are as follows:

The scoring character defaults thought-1, indicating that the article had not been graded. Of course, some people will now say that the design of the table is very unreasonable, because an article will not be rated once, should be able to comment on each user, yes, we are here just to demonstrate the Jrating plug-in using Ajax for the persistence of operations, because it is demo, so all Cong.
Create a new Web page to display the title, content, and rating plugin for the first article (ID 1), see the foreground code:
Copy Code code as follows:

<title></title>
<link href= "Script/jrating/jrating.jquery.css" rel= "stylesheet" type= "Text/css"/>
<script src= "Script/jquery-1.7.min.js" type= "Text/javascript" ></script>
<script src= "Script/jrating/jrating.jquery.js" type= "Text/javascript" ></script>
<script type= "Text/javascript" >
$ (function () {
$ (". Therating"). Jrating ({
LENGTH:20,
Phppath: ' tempajax.aspx/updatecomment '//address becomes a static function under an ASPX-type Web page, which we'll see later!
});
});
</script>
<body>
<form id= "Form1" runat= "Server" >
<div>
<asp:label id= "Label1" runat= "Server" text= "title:" ></asp:Label>
<asp:label id= "Page1_title" runat= "Server" text= "></asp:label><br/>
<asp:label id= "Page1_body" runat= "Server" text= "></asp:label><br/>
<div id= "16_1" class= "therating" ></div>
</div>
</form>
</body>

Background CS code is as follows:
Copy Code code as follows:

protected void Page_Load (object sender, EventArgs e)
{
if (! Page.IsPostBack)
{
Tempentities CBX = new Tempentities (); Using the Entity Framework to get the data table
var Page1 = cbx.jRatingArticles.Where (m => m.id = = 1). Singleordefault ();
Page1_title. Text = Page1.title;
Page1_body. Text = Page1.body;
}
}

To reduce the database connection code, I used the Entity Framework and mapped only one table (jratingarticle), which is what we see above. Gets the article object with ID 1 and assigns the corresponding property to the Text property of the label control.
The page effect is as follows

We can see the above front page in the JS code, there is such a statement:
Phppath: ' Tempajax.aspx/updatecomment '
It indicates that when the mouse clicks on the plugin, to send the data via Ajax address, here we use the. NET page technology to handle this asynchronous request. Tempajax.aspx's background CS code is as follows:
Copy Code code as follows:

[WebMethod ()]
public static void Updatecomment (int idbox, int rate)
{
Tempentities CBX = new Tempentities ();
var Page1 = cbx.jRatingArticles.Where (m => m.id = = 1). Singleordefault ();
Page1.is_comment = rate;
Cbx. SaveChanges ();
}

At this point, we also need to modify the original file of the Jrating plugin, and replace the $.post function in the mouse click Processing function as follows:
Copy Code code as follows:

$.ajax ({
Type: "POST",
Url:opts.phpPath,
Data: ' {"Idbox": "' + Idbox + '", "rate": "' + Rate + '"} ',
ContentType: "Application/json; Charset=utf-8 ",
DataType: "JSON"
});

Why change the source file because I want to change the contenttype attribute of the AJAX request, send the request data using the JSON format, the default is application/x-www-form-urlencoded
OK, everything is all right, look at the implementation effect (the selection ratio is 16, 16 red stars):

look at the changes in the database :

The test was successful! Today's study is here, I hope this study notes for everyone can help!

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.