gpt4 book ai didi

javascript - 在函数中插入代码

转载 作者:行者123 更新时间:2023-12-02 17:01:09 25 4
gpt4 key购买 nike

我使用此代码在图像加载时显示加载程序效果:

$(function(){
jQuery('figure').append('<div class="loader"><div class="bounce1"></div><div class="bounce2"></div><div class="bounce3"></div></div>');
jQuery('.img').load(function(){
jQuery('.loader').remove();
});
});

但我希望这段代码位于一个函数中,以便我可以在任何图像上调用它。 JSFIDDLE

最佳答案

您传递给 $() 的内容已经是一个匿名函数。

如果您想在其他地方调用它,您可以简单地给它一个名称,例如

function showSoader(){
jQuery('figure').append('<div class="loader"><div class="bounce1"></div><div class="bounce2"></div><div class="bounce3"></div></div>');
jQuery('.img').load(function(){
jQuery('.loader').remove();
});
}

您可以将其绑定(bind)到ready,如$(showSoader),并在其他任何地方调用它,如showSoader()

如果您想将其推广到多个元素,只需指定一个参数来访问该元素即可:

function showSoader(selector){
var $elm = $(selector);
$elm.append('<div class="loader"><div class="bounce1"></div><div class="bounce2"></div><div class="bounce3"></div></div>');
$elm.find('.img').load(function(){
$elm.find('.loader').remove();
});
}

您称之为 showSoader("#myImgContainer")

值得注意的是:

Caveats of the load event when used with images

A common challenge developers attempt to solve using the .load() shortcut is to execute a function when an image (or collection of images) have completely loaded. There are several known caveats with this that should be noted. These are:

  • It doesn't work consistently nor reliably cross-browser
  • It doesn't fire correctly in WebKit if the image src is set to the same src as before
  • It doesn't correctly bubble up the DOM tree
  • Can cease to fire for images that already live in the browser's cache

关于javascript - 在函数中插入代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25707402/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com