jquery implementation wait for the specified element to be loaded (can be converted to pure JS version)

Source: Internet
Author: User

Http://www.poluoluo.com/jzxy/201307/233374.html

The code is as follows:


jQuery.fn.wait = function (func, times, interval) {
var _times = Times | | -1,//100 times
_interval = Interval | | 20,//20 milliseconds per
_self = this,
_selector = this.selector,//Selector
_iintervalid; Timer ID
if (this.length) {//If you have already obtained it, execute the function directly
Func && Func.call (this);
} else {
_iintervalid = setinterval (function () {
if (!_times) {//Is 0 exit
Clearinterval (_iintervalid);
}
_times <= 0 | | _times--; If it's a positive number--

_self = $ (_selector); Select again
if (_self.length) {//to decide whether to take
Func && Func.call (_self);
Clearinterval (_iintervalid);
}
}, _interval);
}
return this;
}


The use of the method is also very simple, only 3 parameters.
Func is a callback function that executes when the specified element is present.
The Times is the number of detections, which by default is-1, which is detected until it appears.
Interval is the detection interval, which defaults to 20 milliseconds at a time.

We modify the previous code

.The code is as follows:
$ ("#btn_comment_submit"). Wait (function () {//waits for the #btn_comment_submit element to load
This.removeclass ("Comment_btn"). AddClass ("btn"); Submit button
This is the $ ("#btn_comment_submit")
});

$ ("#widget_my_zzk"). Wait (function () {//waits for the #widget_my_zzk element to load
$ (". Div_my_zzk"). AddClass ("Input-append"); Search box
$ (". Btn_my_zzk"). Removeclass ("Btn_my_zzk"). AddClass ("btn"); Search button
});


is not very simple,

Of course, you can still do $ ("#id") without destroying the chain structure of jquery. Wait (function () {}). Hide ();
But then think, the elements are not loaded, continue to chain down no meaning, but forget, do not change, so it. Hehe:-)

jquery implementation wait for the specified element to be loaded (can be converted to pure JS version)

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.