简体   繁体   English

页面上的Javascript函数调用onload和onclick吗?

[英]Javascript function call on page both onload and onclick?

I need help with changing a function that is called once the page loads, and anytime afterwards when the user clicks on a certain div with an ID. 我需要更改页面加载后以及用户单击带有ID的特定div之后的任何时间调用的函数的帮助。 So far I have this: 到目前为止,我有这个:

window.onload=function() {
//Do your stuff, JS!
}

Yes, I barely know any JS... 是的,我几乎不知道任何JS ...

EDIT: I will include my JS function (I didn't make it myself, obviously another nice and smarter person did :P) 编辑:我将包括我的JS函数(我自己没有做,显然是另一个不错的人:P)

    function() {
    var maxHeight = 0;
    //get the column containers
    var colsA = document.getElementById("Content").childNodes;

    //get the height of the tallest column
    for(var i=0; i < colsA.length; i=i+1) {
         if(colsA[i].clientHeight > maxHeight) maxHeight = colsA[i].clientHeight;
    }

 //set all the column containers heights to maxHeight
    for(var i=0; i < colsA.length; i=i+1) {
         if(colsA[i].nodeType == 1) colsA[i].style.height = maxHeight+'px';
    }
} 

What it does: I have a div container that houses x number of column divs. 它的作用:我有一个div容器,可容纳x个列div。 These columns vary at height due to content. 这些列的高度因内容而异。 This function makes all the divs heights the same. 此功能使所有div高度相同。

When my page loads, this code runs flawlessly. 当我的页面加载时,此代码可以完美运行。 However afterwards, it doesn't. 但是之后,事实并非如此。 I have some collapsible divs that house extra information, when a user clicks it will push the height further. 我有一些可折叠的div,其中包含额外的信息,当用户单击它时,它将进一步提高高度。 This is why I thought of an onclick for that id... unfortunately the id is dynamically generated by php. 这就是为什么我想到该ID的onclick的原因。不幸的是,该ID是由php动态生成的。

You can define a function separately and then bind it to multiple event handlers: 您可以单独定义一个函数,然后将其绑定到多个事件处理程序:

function myHandler(){...}
window.onload = myHandler;
myElement.onclick= myHandler;
...

This should fix it: 这应该解决它:

function f() {
    // do your stuff
}

window.onload = f;
document.getElementById("myButton").onclick = f;

Another way: 其他方式:

window.onload=function() {
//Do your stuff, JS!
}

yourElement.onclick = window.onload;

In the end it does not matter how you do it. 最终,您的操作方式无关紧要。 Functions are first class objects, so you just need to have a reference to the function. 函数是一流的对象,因此您只需要引用该函数即可。


To learn more about JavaScript, have a look at the MDC JavaScript Guide . 要了解有关JavaScript的更多信息,请参阅MDC JavaScript Guide

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

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