加载 DOM 后立即在具有特定类的元素上运行函数,而不是使用事件处理程序
我有一个简单的函数,我想在具有特定类的所有元素上运行。我希望这个函数在 DOM 加载后立即运行;不在事件处理程序上。
下面是将在悬停等事件处理程序上运行的代码。如何让它在 DOM 加载后立即运行?
$(document).ready(function(){
var displayname = $(".displayname");
function alignSpans(){
var spanheight = this.offsetHeight;
var cssbottom = spanheight + "px";
this.style.bottom = cssbottom;
}
displayname.hover(alignSpans);
});
displayname.alignSpans();
不起作用
I have a simple function which I want to run on all elements with a certain class. I want this function to be run as soon as the DOM is loaded; not upon an event handler.
Below is the code that will run on an event handler like hover. How do I make it run as soon as the DOM is loaded?
$(document).ready(function(){
var displayname = $(".displayname");
function alignSpans(){
var spanheight = this.offsetHeight;
var cssbottom = spanheight + "px";
this.style.bottom = cssbottom;
}
displayname.hover(alignSpans);
});
displayname.alignSpans();
does not work
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
假设
displayname
是一个 jQuery 对象,您可以使用.each()
使用this
作为包含的 DOM 元素来调用回调函数(这与事件处理程序的约定非常方便)Assuming
displayname
is a jQuery object, you can use.each()
to call a callback function usingthis
as the contained DOM elements (which is very conveniently the same convention as an event handler)这就是 .each() 函数的用途。我也让你的代码更加高效:
That's what the .each() function is for. I've made your code a bit more efficient too: