简体   繁体   中英

How to asynchronously update dynamically generated HTML control in Javascript

I have a method getTextContent that will be called indirectly through a user's click (method getTextContent is passed to an API function that registers it with some event).

The method returns a string that is simply a string of HTML, that is then displayed to the user in an API generated control.

What I would like to do is asynchronously update one of the HTML controls. I believe I can create a uniqueID and name that HTML control with that ID for alter reference.

My hangup is this: How do I pass the unique ID to the return/success method ( SucceededCallback ) of the webservice.

Webservice1.Foo(param1, SucceededCallback, FailedCallback);

so that I have a function like

function SucceededCallback(result, uniqueID) {
   document.getElementById(uniqueID).value = result;
}

I suppose I could create a global variable, but that seems improper

You can use Function.prototype.bind to bind the context to the function.

Webservice1.Foo(param1, SucceededCallback.bind(uniqueID), FailedCallback.bind(uniqueID));

Then the function would be:

function SucceededCallback(result) {
    document.getElementById(this).value = result;
}

Or you could use a closure:

Webservice1.Foo(param1, function(result) {
    SucceededCallback(result, uniqueID);
}, function(result) {
    FailedCallBack(result, uniqueID);
});

Also, instead of passing the ID, you could pass the DOM element itself, so you don't have to call getElementById .

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