Method for detecting element occurrences.
Although it is based on JQuery, but the code is very concise, can be modified into a pure JS version.
Text
JQuery.fn.wait =function(Func, Times, Interval) {var _times = Times | | -1,100 times _interval = Interval | |20,20 ms Each _self =This, _selector =This.selector,Selector _iintervalid;//Timer ID if (this.length) {//if already acquired, execute function func && func.call (this);} else {_iintervalid = setinterval (function< Span class= "Hljs-params" > () {if (!_times) {//is 0 exit Clearinterval (_iintervalid); } _times <= 0 | | _times--; //if it is positive--_self = $ (_selector); //again select if (_self.length) {// Determine 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
Text
$("#btn_comment_submit"). Wait (function () {//wait #btn_comment_ The load of the submit element this.removeclass ( "comment_btn"). AddClass ( "btn"); //submit button //here is the $ ("#btn_comment_submit")}); $ (function () {//wait for the #widget_my_zzk element to load $ (" Input-append "); //search box $ ( "btn"); //search button});
is not very simple,
Of course, you can still do $ ("#id") without destroying the chain structure of jquery. Wait (function () {}). Hide ();