gpt4 book ai didi

Javascript 函数在页面加载时触发,而不是在点击时触发

转载 作者:太空宇宙 更新时间:2023-11-03 22:48:05 26 4
gpt4 key购买 nike

函数“display()”在页面加载时触发,而不是在点击时触发。我不确定为什么。当我将功能更改为“警报”时,它会更明显地显示问题。我想尝试更改参数变量,但没有用。我使用了 x 和内容。我如何让它停止加载?它也只加载前两个 div。我在单独的 javascript 页面上使用了相同的格式,并且效果很好。

我没有
https://jsfiddle.net/ethacker/92r0apd9/JS:

var firstTrimesterButton = document.getElementById('firstTri');
var secondTrimesterButton = document.getElementById('secTri');
var thirdTrimesterButton = document.getElementById('thirdTri');
var firstThreeMonthsButton = document.getElementById('firstThreeMonths');
var secondThreeMonthsButton = document.getElementById('secThreeMonths');
var thirdThreeMonthsButton = document.getElementById('thirdThreeMonths');
var fourthThreeMonthsButton = document.getElementById('fourthThreeMonths');
var toddlersButton = document.getElementById('toddlers');

var fTContent = document.getElementById('fTContent');
var sTContent = document.getElementById('sTContent');
var tTContent = document.getElementById('sTContent');
var firstTMContent = document.getElementById('sTContent');
var sTMContent = document.getElementById('sTContent');
var tTMContent = document.getElementById('sTContent');
var fourthTMContent = document.getElementById('sTContent');
var toddlersContent = document.getElementById('sTContent');

//event listeners
firstTrimesterButton.addEventListener("click", display(fTContent));
secondTrimesterButton.addEventListener("click",display(sTContent));
thirdTrimesterButton.addEventListener("click", display(tTContent));
firstThreeMonthsButton.addEventListener("click", display(firstTMContent) );
secondThreeMonthsButton.addEventListener("click", display(sTMContent));
thirdThreeMonthsButton.addEventListener("click", display(tTMContent));
fourthThreeMonthsButton.addEventListener("click",display(fourthTMContent));
toddlersButton.addEventListener("click",display(toddlersContent));

//function
function display(content) {
content.style.display= 'inline';
}

最佳答案

您应该将对回调函数的引用放入您的addEventListener。如果您设置 display(fTContent) - 您只需运行此函数。正确的触发是

firstTrimesterButton.addEventListener("click", function() {
display(fTContent);
});

关于Javascript 函数在页面加载时触发,而不是在点击时触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41317671/

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