简体   繁体   中英

Alert After jQuery Function is Finished

I'm trying very hard to figure out how to get a JS alert to appear only after a previous script ( a glossary word replacement script ) has finished. Getting this javascript/jquery to run in order is giving me a headache as it either runs out of order, or the second part doesn't run at all.

Here is the code that is presently working WITHOUT the alert:

<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script src="jquery.zglossary.min.js" type="text/javascript"></script>

<script>
$(document).ready(function () {
    $('body').glossary('listofwords.json');
    //want alert('finished') to happen after glossary word replacement is finished replacing words here
});
</script>

</head>

I've tried a lot of different things trying to get an alert to happen where that comment is, and either the alert happens immediately before any words are replaced by the zglossary script, an example of that would be:

<script>
$(document).ready(function () {
    $('body').glossary('listofwords.json');
    alert('finished');
});
</script>

Or the script will replace all the words and no alert happens at all. An example of that would be:

<script>
$(document).ready(function () {
    $('body').glossary('listofwords.json');
}, function() {
    alert('finished');
});
</script>

Another example of that happening (words are replaced, but no alert happens) that I've tried would be:

<script>
$(document).ready(function () {
    $('body').glossary('listofwords.json', function() {alert('finished');} );
});
</script>

I really just can't figure this out. I'd appreciate any help

I've never used this glossary plugin before - but I downloaded the source and I see the issue is clearly because the glossary plugin does not provide any callback after the JSON data is asynchronously downloaded. Any solution that is not hacky will require a slight modification to the library itself.

Here is a quick way you could do it

By adding this line

typeof options.callback == 'function' && options.callback();

At the end of the success: function(data) {

Then your code would simply be this:

<script>
$(document).ready(function () {
    $('body').glossary('listofwords.json', {callback:function() {alert('finished');}} );
});
</script>

Which is similar to your last example, only it puts the callback into an options JSON which is what the plugin expects.

I have no idea what's "Glossary", but you might find a solution with Deferred object supplied by jQuery api . Deferred helps to handle json calls, especially the .done() method to set a caalback when the call is finished.

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