jquery - How to make a continuous listener in javascript? -
i learning perhaps question rephrased or re-worded.
- when click div=> variable= variable+1;
- what want when 'variable===3', console.log('i 3).
my script not doing trying do, try.
<script type="text/javascript"> element = document.getelementbyid("id"); variable=0; function loading(){ element.addeventlistener("click",function(){ variable=variable+1; console.log(variable); }); }; function check(){ if(variable===3){console.log('i 3');}; }; loading(); check(); </script>
should call check() each time object clicked? or should create listener call check() every time 'variable' changing? or solutions?
call check
event handler:
function loading(){ element.addeventlistener("click",function(){ variable=variable+1; check(); console.log(variable); }); }
calling check
whenver variable
changes option variable.
if want check time value of changes, use object property instead, setter:
var obj = (function() { var value = 0; return { value() { return value; }, set value(newvalue) { value = newvalue; if (value == 3) { console.log("i 3"); } } } })();
then:
function loading(){ element.addeventlistener("click",function(){ obj.value = obj.value + 1; // or ++obj.value; console.log(obj.value); }); }
whenever change value of obj.value
, setter function called, , can check there.
note feature added in es5 (2009), it's not present in older javascript engines such 1 in ie8.
some other notes:
your code falling prey the horror of implicit globals: declare variables.
;
don't go @ end of function declarations, or blocks. statements don't end block.consistent indentation aids readability.
variable = variable + 1;
fine, have option of being more concise:++variable;
so:
var element = document.getelementbyid("id"); var variable = 0; function loading(){ element.addeventlistener("click",function(){ ++variable; console.log(variable); check(); }); } function check(){ if (variable===3) { console.log('i 3'); } } loading(); check();
Comments
Post a Comment