简体   繁体   English

如何在外部JS脚本完成运行后运行函数

[英]How to run a function after an external JS script finishes running

I am trying to understand how to ensure my code runs after an external JS file has finished running. 我试图了解如何确保我的代码在外部JS文件运行完毕后运行。

If you need a specific implementation, you can look at this SO question, which I am trying to help answer: How to get the last table row no matter the sort? 如果你需要一个特定的实现,你可以看看这个SO问题,我试图帮助回答: 如何获得最后一个表行,无论排序?

TDLR : The script found in bootstrap-sortable.js runs a table sort. TDLRbootstrap-sortable.js中的脚本运行表排序。 After this table sort is complete; 此表排序完成后; I want to make it so that I can run a snippet, which will add a simple CSS class to the last element in the freshly sorted table. 我想这样做,以便我可以运行一个片段,它将一个简单的CSS类添加到新排序表中的最后一个元素。 The adding of the class can easily be achieved by this JQuery snippet: 通过此JQuery代码段可以轻松实现类的添加:

var lastRow = $(this).closest("table").find("tbody tr:last");

if(!lastRow.hasClass("dropup")){
    // Removing dropup class from the row which owned it
    $(this).closest("table").find("tbody tr.dropup").removeClass("dropup");
    // Adding dropup class to the current last row
    lastRow.addClass("dropup");
}

I would like to know: 我想知道:

  1. Is it possible to run my script after the external script is done running? 外部脚本运行完成后是否可以运行我的脚本?
  2. If not, can you explain why? 如果没有,你能解释一下原因吗?
  3. I have already considering modifying bootstrap-sortable.js to add my script to it, is this the best recommendable approach? 我已经考虑修改bootstrap-sortable.js来添加我的脚本,这是最好的推荐方法吗?

Bonus round! 奖金回合! (only if you feel you need the challenge). (只有当你觉得自己需要挑战时)。

Is there a better, do-it-yourself, solution for sorting the table other than using bootstrap-sortable.js for the linked question? 除了使用bootstrap-sortable.js作为链接问题之外,还有一个更好的,自己动手的解决方案来排序表吗?

Thanks everyone! 感谢大家!

I want to thank Dave Newton for leading me to the answer to this question which is quite simple. 我要感谢Dave Newton带领我回答这个问题很简单。

JSFiddle 的jsfiddle

$(document).ready(function() {
  $("#MyTable").on('sorted', function(){
    var lastRow = $("#MyTable").find("tbody tr:last");
      // Removing dropup class from the row which owned it
      $("#MyTable").find("tbody tr.dropup").removeClass("dropup");
      // Adding dropup class to the current last row
      lastRow.addClass("dropup");
  });
});

This is awesome, simple and lightweight, it also adheres to the linked question. 这很棒,简单,轻巧,也坚持链接的问题。 Thanks Dave! 谢谢戴夫!

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

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