简体   繁体   中英

How can I run some code on all the nodes in a tree?

I want to run some code on all my treeView nodes depending on a value returned from the database and repeat this until a certain value is returned.

I was thinking that:

  1. Give all my tree nodes the same css class so I can access them from JQuery
  2. have a timer in my JQuery function that used ajax to go to the database, when a certain value is returned then stop the timer

Two questions here. How can I make my function run for each of the nodes and how do I do a timer in JavaScript, so:

$(function(){
    $('cssClassOfAllMyNodes').WhatFunctionToCallHere?((){

//How do I do Timer functionality in JavaScript? ForEachTimeInterval { //use Ajax to go to database and retrieve a value AjaxCallBackFunction(result) { if (result = 1) //How to stop the timer here? } } });

});

Hope i'm clear. Thanks a lot


thanks a lot for the answer. And i would like you to comment on the design.

Bascially what i'm trying to acheive is a Windows Wokflow type functionality where each node in my tree updates its image depending on its status, where its status is got from querying the database with a key unique to the tree node. I'm open to ideas on other ways to implement this if you have any. thanks again

Without commenting on your design you can refer to these

$.each()

setTimeout() or setInterval()

You can do:

$(function(){
  $('cssClassOfAllMyNodes').each(function (){
    // Do something with "this" - "this" refers to current node.
  });
});

Te proper way to handle timers in JS is to have a reference to each timeout or interval and then clearing them out.

The difference between them is:

  • The timeout will only run once, unless stopped before;
  • The interval will run indefinitely, until stopped.

So you can do something like:

var delay = 2000; // miliseconds
var timer = setTimeout("functionToBeCalled", delay);
clearTimeout(timer); // whenever you need.

Please note you can pass a string to setTimeout (same with setInterval) with the name of the function to be called. Or you could pass a reference to the function itself:

var callback = function () { alert(1); };
var timer = setTimeout(callback, delay);

Be sure not to set an Interval for AJAX requests, because you response might be delayed and successive calls to the server could eventually overlap.

Instead, you should call setTimeout and when the answer arrives then call setTimeout again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM