简体   繁体   English

重构重复的jQuery代码

[英]Refactor repetitive jQuery code

I would like to refactor the following piece of code from an old project. 我想从一个旧项目重构以下代码片段。

$("#foo_div").html('').load('/some/route/', function(){
    // ... 
});

$("#bar_div").html('').load('/some/route/', function(){
    // ... 
});

$("#baz_div").html('').load('/some/route/', function(){
    // ... 
});

What the code does is to make an AJAX call and get some HTML result which will be then appended to the three divs. 代码的作用是进行AJAX调用并得到一些HTML结果,然后将其附加到三个div。 The result is always the same, so there's no need to have three identical calls. 结果总是一样的,所以不需要有三个相同的调用。

Is there any way I could rewrite this code in order to run the call a single time, store the output and then append it to the three divs? 有没有什么办法可以重写这段代码,以便一次运行调用,存储输出,然后将它附加到三个div?

I don't want to use "async" so I'm looking for other means to do it. 我不想使用“异步”,所以我正在寻找其他方法来做到这一点。

Thanks. 谢谢。

选择所有三个元素并调用load()

$("#a, #b, #c").html("").load('foo.html', function(){});

You can use the jQuery.get function to perform this. 您可以使用jQuery.get函数来执行此操作。 See https://api.jquery.com/jquery.get/ 请参阅https://api.jquery.com/jquery.get/

$.get( "...", function( data ) {
  $("#foo_div").html(data);
  $("#bar_div").html(data);
  $("#baz_div").html(data);
});

Assuming those id s are for div s you can reduce the query to be any div that has an id that ends in _div 假设这些iddiv你可以将查询减少为id为以_div结尾的任何div

$( "div[id$='_div']" ).html('').load('/some/route/', function(){
    // ... 
});

You can just group the ids in the jQuery selector 您可以只在jQuery选择器中对id进行分组

$.ajax( "...", function( data ) {
  $("#foo_div, #bar_div, #bar_div").html(data);
});

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

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