简体   繁体   English

如何在onclick事件上顺序调用javascript方法

[英]how to call javascript methods sequentially on onclick event

I need to call two functions sequentially (means one by one) in javascript on onclick event. 我需要在onclick事件的javascript中依次调用两个函数(一个接一个)。

The requirement is to get the data from the backend and then make the cell highlight. 要求是从后端获取数据,然后突出显示单元格。 Below code snippet is used for this: 下面的代码段用于此目的:

cell1.onclick=function() {
    getData("FileName");
    setTimeout("setHighlight('FileName')", 500);
};

Currently i am using the setTimeout for calling the second method after a delay of 500ms. 目前,我正在使用setTimeout在延迟500毫秒后调用第二种方法。

The problem with above code is if getData method takes more than 500ms to get the data from backend then in that case cell would not get highlighted. 上面代码的问题是,如果getData方法花费超过500ms的时间从后端获取数据,则在这种情况下,单元格将不会突出显示。

Is there any way to do this? 有什么办法吗?

Thanks Jyoti 感谢Jyoti

To get data from the backend, you probably are using AJAX. 为了从后端获取数据,您可能正在使用AJAX。

And in the callback function you are populating the data. 在回调函数中,您正在填充数据。 After this step, call the highlight function. 此步骤之后,调用突出显示功能。

You probably have something like this: 您可能有这样的事情:

      xmlHttp.onreadystatechange = function() 
      { 
         if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
         { 
            // do something with the response here
            highlightData();  //<---- the function to highlight data
         } 
      } 

You should add another parameter to getData, which is a function to execute when you have the data. 您应该向getData添加另一个参数,该参数是拥有数据时要执行的功能。 So, 所以,

function getData(filename, callback) {
  // get the data
  // when you have the data, do callback(filename);
}

then you can do 那你就可以

getData("FileName", setHighlight);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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