Summarize a few about jQuery usage

About jquery usage

content:

  • $.trim()
  • $.inArray()
  • $.getJSON()
  • event delegate on

Enter the text ing...

1. jQuery.trim(str)
Explanation: Remove spaces from the beginning and end of a string.
var str='   hello hi    '; 
var new_str=$.trim(str);
console.log(str.length)        // 12
console.log(new_str.length)    // 8
For example, when submitting a form, to obtain the user's val() value to prevent the space entered by the user from affecting subsequent operations, you can use trim() here
var username=$.trim($('#username').val()); 

2.jQuery.inArray( value, array [, fromIndex ] )
Its method is similar to JavaScript's native .indexOf() method, which returns -1 when no matching element is found. $.inArray() returns 0 if the first element of the array matches value (parameter).
var fruits=['apple','banner','orange','pear'];
var mine='orange';
var res=$.inArray(mine,fruits);
if(res==-1){ // 不存在
	console.log('sorry,没有你喜欢的!')
}else{
	console.log('有你的!')
}
By the way, recall the usage of native js for string indexOf
语法:stringObject.indexOf(searchvalue,fromindex)

Notice:

(1) The indexOf() method is case sensitive
(2) If the string value to be retrieved does not appear, the method returns -1. Detected to return 0.
var str='hello hi see';
var searchvalue=str.indexOf('a');
if(searchvalue==-1){
	console.log('该字符串不存在!') // 该字符串不存在
}else{
	console.log(searchvalue)
}
3.jQuery.getJSON()
Simply put, it is to get json data through ajax request.
Specifically, it is used to obtain remote JSON-encoded data through AJAX requests in the form of HTTP GET.
A few points to expand:

(1) JSON是一种数据格式,JS原生支持JSON格式,通过jQuery.getJSON()从服务器获得的JSON数据,jQuery会先尝试将其转为对应的JS对象。
(2) 如果请求的URL中包括"callback=?"等类似的部分,jQuery会自动将其视作JSONP,并执行对应的回调函数来获取JSON数据。
(3) 服务器返回的JSON数据必须符合严格的JSON语法,例如:所有属性名称必须加双引号,所有字符串值也必须加双引号(而不是单引号)。
(4) 该函数是通过异步方式加载数据的。
(5) 该函数属于全局jQuery 对象。

Here's its syntax:

// 请求目标url 类型字符串  
// 发送请求传递的数据 可选 
// 请求成功执行的回调函数
jQuery.getJSON( url [, data ] [, success ] )
For example: to get the JSON data of "/action.php?m=list&page=2&size=10", a dialog box will pop up when the acquisition is successful
 
$.getJSON( "/action.php?m=list", { page: 2, size: 10  }, function(data, textStatus, jqXHR){
    // 如果服务器返回的JSON格式的数据是 [ {"id":11, "title":"文章11"}, {"id":12, "title":"文章12"}, {"id":13, "title":"文章13"} ]
    // jQuery将获取的JSON格式数据转换为JS数组
    for(var i in data){
        var obj = data[i];
        alert( obj.title );
    }

} );

The above code: The callback function has three parameters that can console.log() them out, attach a screenshot

getjson_callback parameter map

4. Bind the event on
The first thing to understand here: event delegation
事件委托:
通俗地来讲,就是把一个元素响应事件(click、keydown......)的函数委托到另一个元素;

举个例子:
比如一个宿舍的同学同时快递到了,一种方法就是他们都一个个去领取,还有一种方法就是把这件事情委托给宿舍长,让一个人出去拿回来所有快递,然后再根据收件人一一分发给每个宿舍同学;

在这里,取快递就是一个事件,每个同学指的是需要响应事件的 DOM 元素,而出去统一领取快递的宿舍长就是代理的元素,所以真正绑定事件的是这个元素,按照收件人分发快递的过程就是在事件执行中,需要判断当前响应的事件应该匹配到被代理元素中的哪一个或者哪几个。

For a detailed explanation of event delegation , you can learn more about it here.
continue...
Usually we have seen the usage of binding event on in the following two ways
.on(events, callback) 只能绑定页面已有元素的事件。
.on(events, selector, callback) 则是在 已有的元素 上绑定 代理的 事件处理器 (addEventListener 实际上在该已有元素上调用),但只有事件的实际 source 是其子代元素并且符合 selector 时, callback 才会以该实际 source 为 this 指向的对象被调用。
The first one is actually the same as directly binding click
$(selector).click(function (){})
$(selector).on('click ,function (){})
The second is the event delegation
It has two meanings:
One is that the existing dom node has events.
The second is that the newly added dom node also has events.

So why use delegated events?

Generally speaking, DOM needs to have event handlers, we will just set event handlers for it directly. What if there are a lot of DOMs that need to add event handlers? For example, we have 100 li, and each li has the same click event. Maybe we will use the for loop method to traverse all the li and then add events to them. What effect will this have?

In JavaScript, the number of event handlers added to the page will be directly related to the overall performance of the page, because it is necessary to constantly interact with the DOM node. The more times the DOM is accessed, the number of browser redraws and reflows. The more, the longer the interactive ready time of the entire page, which is why one of the main ideas of performance optimization is to reduce DOM operations;

If you want to use event delegation, you will put all the operations in the js program, and you only need to interact with the DOM once, which can greatly reduce the number of interactions with the DOM and improve performance;

The principle of event delegation:

Event delegation is implemented using the bubbling principle of events.

Why is the event bubbling?

That is, the event starts from the deepest node, and then gradually propagates up the event.

Keep reading:

There is such a node tree on the page, div>ul>li>a; for example, add a click event to the innermost a, then this event will be executed layer by layer, in the order of a>li>ul>div , there is such a mechanism, then we add a click event to the outermost div, then when the ul, li, and a inside do click events, they will bubble up to the outermost div, so they will all be triggered, this is the event delegation , delegate their parent to execute the event on their behalf.

Summarize again the advantages of delegation
(1) Reduce memory consumption
<ul id="list">
  <li>item 1</li>
  <li>item 2</li>
  <li>item 3</li>
  ......
  <li>item n</li>
</ul>
// ...... 代表中间还有未知数个 li
$('ul').on('click','li',function(){
	...
})
(2) Dynamic binding events

In actual projects, we often need to dynamically add or remove list item elements through AJAX or user operations, so every time we change, we need to re-bind events for the newly added elements and unbind events for the elements that are about to be deleted;

If you use event delegation, there is no such trouble, because the event is bound to the parent layer and has nothing to do with the increase or decrease of the target element. The execution to the target element is matched in the process of actually responding to the execution of the event function. ;

So using events can reduce a lot of repetitive work in the case of dynamically binding events.

 //操作Partner账号列表
    //增:
    $(document).on("click",'.add_to_list',function(){
     	...
     });
     //删:
    $(document).on("click",'.del_to_list',function(){
     	...
     })
Summary: Events suitable for event delegation: click, mousedown, mouseup, keydown, keyup, keypress.
Note: Although mouseover and mouseout also have event bubbling, they need special attention when dealing with them, because their positions need to be calculated frequently, and it is not easy to deal with. In addition, such as focus, blur, etc., there is no need for bubbling itself. The characteristics of , naturally can not use event delegation.

Knowledge is the accumulation of...

come on!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324406284&siteId=291194637