在外部设置 onclick 函数 javascript
setting onclick function in external javascript
我有一段功能代码设置如下。一个 .html 文件,基本上只包含由 "id" 标识的 2 个 div。 "head" 引用外部 .css 文件,在 "body" 末尾引用外部 .js。这个组合有效。
但是当我将 .js 引用移动到 "head" 时,代码不起作用。具体来说,其中一个 div 的 .onclick 函数 (reactionShapeId.onclick) 的定义未使用 errmsg "TypeError: Cannot set property 'onclick' of null" 设置。因为一旦放入head,.js代码还不知道body中的div(reactionShape),即reactionShapeId为null。
avoid/handle 这种依赖的正确方法是什么?下面是我的 .js 代码。谢谢。
var reactionShapeId = document.getElementById("reactionShape");
var createdTime, clickedTime;
var maxDelay = 5000; // milliseconds
console.log(reactionShapeId);
// set absolute limits to the shape - equilateral is assumed
var maxLength = Math.min(300,window.innerWidth,window.innerHeight);
var minLength = Math.min(50,maxLength);
var minOpacity = 0.25;
// dynamically determined shape variables
var shapeLength;
var shapeBorderRadius; // square or circle
var posX, posY;
var colourRed, colourGreen, colourBlue, colourOpacity;
// statistics
var maxTrials = 10;
var trialResults = new Array();
var trialCounter = 0;
var trialTotal = 0;
var trialAverage;
function makeShape() {
trialCounter = trialCounter + 1;
// first determine properties for shape
shapeLength = minLength + (maxLength-minLength) * Math.random();
if (Math.round(Math.random()) == 1) {
shapeBorderRadius = 0;
} else {
shapeBorderRadius = shapeLength / 2;
}
posX = (projectReactionTester.offsetWidth - shapeLength) * Math.random();
posY = (projectReactionTester.offsetHeight - shapeLength) * Math.random();
colourRed = Math.floor(256 * Math.random());
colourGreen = Math.floor(256 * Math.random());
colourBlue = Math.floor(256 * Math.random());
colourOpacity = minOpacity + (1-minOpacity) * Math.random();
// tidy up
if (colourRed==256) colourRed=255;
if (colourGreen==256) colourGreen=255;
if (colourBlue==256) colourBlue=255;
console.log(shapeLength, shapeBorderRadius, posX, posY,
colourRed, colourGreen, colourBlue, colourOpacity,
trialCounter, trialTotal);
// setting of properties must be done altogether
reactionShapeId.setAttribute("style",
"width:" + shapeLength + "px;"
+ "height:" + shapeLength + "px;"
+ "border-radius:" + shapeBorderRadius + "px;"
+ "position: relative;"
+ "left:" + posX + "px;"
+ "top:" + posY + "px;"
+ "background-color:rgba(" + colourRed + ","
+ colourGreen + ","
+ colourBlue + ","
+ colourOpacity + ");");
// then set delay timer
// .display must be set to "block" instead of "inline"
var delayTime = maxDelay * Math.random();
console.log(delayTime);
setTimeout(function() {
createdTime = Date.now();
reactionShapeId.style.display = "block";
},delayTime);
}
reactionShapeId.onclick = function() {
clickedTime = Date.now();
trialResults[trialCounter] = clickedTime - createdTime;
trialTotal = trialTotal + trialResults[trialCounter];
this.style.display = "none";
document.getElementById("reactionTime").innerHTML = trialResults[trialCounter];
// display statistics & re-initialize
if (trialCounter == maxTrials) {
trialAverage = trialTotal / trialCounter;
alert("Your average response time over " + trialCounter + " trials is " + trialAverage + " ms");
trialCounter = 0;
trialTotal = 0;
}
// next trial
makeShape();
}
makeShape();
Best practice is you should load your JavaScript in the bottom of the page, right before the closing tag.
更详细的解释,参考这篇博文here
问题是当您的 js 正在执行时 DOM 没有完全加载,特别是您要添加 onclick 事件的元素。当你把它放在 body 的末尾时,到那时 DOM 就被加载了。要实现此调用 makeShape() inside jquery 文档就绪函数。如果你没有使用 jquery 你可以在 onload 事件中使用。
<body onload="makeShape()">
注意:这里我假设 makeShape 是您要调用的函数,否则将其替换为您的函数
编辑
如果上述解决方案不起作用,在head put
<script>
document.addEventListener("DOMContentLoaded", function() {
makeShape();
});
</script>
如果你使用jquery:
$(document).ready(function(){
makeShape();
})
Here you are trying to access an element which don't exists/loaded/added in DOM
- 你可以在html内容后包含js代码(你想在JS代码中引用)。
- 您可以使用 onload 事件来检查何时加载 DOM 执行 js,以确保加载所有 DOM 元素。
HTML
<body>
<div id="showText"></div>
<button type="button" onclick="myFunction()">Click Here</button>
<button type="button" onclick="GLOBAL.myNewFunction()">Click Here</button>
<script src="js/index.js"></script>
</body>
JavaScript - index.js(外部文件)
//The First Method
window.myFunction = function(){
alert("It's working!");
document.getElementById("showText").innerHTML = "This line is written by JavaScript."
}
//The Second Method
(function(GLOBAL){
function myNewFunction(){
alert("It's working!");
document.getElementById("showText").innerHTML = "This line is written by JavaScript."
}
GLOBAL.myNewFunction = myNewFunction;
})(window.GLOBAL || (window.GLOBAL={}));
我有一段功能代码设置如下。一个 .html 文件,基本上只包含由 "id" 标识的 2 个 div。 "head" 引用外部 .css 文件,在 "body" 末尾引用外部 .js。这个组合有效。
但是当我将 .js 引用移动到 "head" 时,代码不起作用。具体来说,其中一个 div 的 .onclick 函数 (reactionShapeId.onclick) 的定义未使用 errmsg "TypeError: Cannot set property 'onclick' of null" 设置。因为一旦放入head,.js代码还不知道body中的div(reactionShape),即reactionShapeId为null。
avoid/handle 这种依赖的正确方法是什么?下面是我的 .js 代码。谢谢。
var reactionShapeId = document.getElementById("reactionShape");
var createdTime, clickedTime;
var maxDelay = 5000; // milliseconds
console.log(reactionShapeId);
// set absolute limits to the shape - equilateral is assumed
var maxLength = Math.min(300,window.innerWidth,window.innerHeight);
var minLength = Math.min(50,maxLength);
var minOpacity = 0.25;
// dynamically determined shape variables
var shapeLength;
var shapeBorderRadius; // square or circle
var posX, posY;
var colourRed, colourGreen, colourBlue, colourOpacity;
// statistics
var maxTrials = 10;
var trialResults = new Array();
var trialCounter = 0;
var trialTotal = 0;
var trialAverage;
function makeShape() {
trialCounter = trialCounter + 1;
// first determine properties for shape
shapeLength = minLength + (maxLength-minLength) * Math.random();
if (Math.round(Math.random()) == 1) {
shapeBorderRadius = 0;
} else {
shapeBorderRadius = shapeLength / 2;
}
posX = (projectReactionTester.offsetWidth - shapeLength) * Math.random();
posY = (projectReactionTester.offsetHeight - shapeLength) * Math.random();
colourRed = Math.floor(256 * Math.random());
colourGreen = Math.floor(256 * Math.random());
colourBlue = Math.floor(256 * Math.random());
colourOpacity = minOpacity + (1-minOpacity) * Math.random();
// tidy up
if (colourRed==256) colourRed=255;
if (colourGreen==256) colourGreen=255;
if (colourBlue==256) colourBlue=255;
console.log(shapeLength, shapeBorderRadius, posX, posY,
colourRed, colourGreen, colourBlue, colourOpacity,
trialCounter, trialTotal);
// setting of properties must be done altogether
reactionShapeId.setAttribute("style",
"width:" + shapeLength + "px;"
+ "height:" + shapeLength + "px;"
+ "border-radius:" + shapeBorderRadius + "px;"
+ "position: relative;"
+ "left:" + posX + "px;"
+ "top:" + posY + "px;"
+ "background-color:rgba(" + colourRed + ","
+ colourGreen + ","
+ colourBlue + ","
+ colourOpacity + ");");
// then set delay timer
// .display must be set to "block" instead of "inline"
var delayTime = maxDelay * Math.random();
console.log(delayTime);
setTimeout(function() {
createdTime = Date.now();
reactionShapeId.style.display = "block";
},delayTime);
}
reactionShapeId.onclick = function() {
clickedTime = Date.now();
trialResults[trialCounter] = clickedTime - createdTime;
trialTotal = trialTotal + trialResults[trialCounter];
this.style.display = "none";
document.getElementById("reactionTime").innerHTML = trialResults[trialCounter];
// display statistics & re-initialize
if (trialCounter == maxTrials) {
trialAverage = trialTotal / trialCounter;
alert("Your average response time over " + trialCounter + " trials is " + trialAverage + " ms");
trialCounter = 0;
trialTotal = 0;
}
// next trial
makeShape();
}
makeShape();
Best practice is you should load your JavaScript in the bottom of the page, right before the closing tag.
更详细的解释,参考这篇博文here
问题是当您的 js 正在执行时 DOM 没有完全加载,特别是您要添加 onclick 事件的元素。当你把它放在 body 的末尾时,到那时 DOM 就被加载了。要实现此调用 makeShape() inside jquery 文档就绪函数。如果你没有使用 jquery 你可以在 onload 事件中使用。
<body onload="makeShape()">
注意:这里我假设 makeShape 是您要调用的函数,否则将其替换为您的函数
编辑
如果上述解决方案不起作用,在head put
<script>
document.addEventListener("DOMContentLoaded", function() {
makeShape();
});
</script>
如果你使用jquery:
$(document).ready(function(){
makeShape();
})
Here you are trying to access an element which don't exists/loaded/added in DOM
- 你可以在html内容后包含js代码(你想在JS代码中引用)。
- 您可以使用 onload 事件来检查何时加载 DOM 执行 js,以确保加载所有 DOM 元素。
HTML
<body>
<div id="showText"></div>
<button type="button" onclick="myFunction()">Click Here</button>
<button type="button" onclick="GLOBAL.myNewFunction()">Click Here</button>
<script src="js/index.js"></script>
</body>
JavaScript - index.js(外部文件)
//The First Method
window.myFunction = function(){
alert("It's working!");
document.getElementById("showText").innerHTML = "This line is written by JavaScript."
}
//The Second Method
(function(GLOBAL){
function myNewFunction(){
alert("It's working!");
document.getElementById("showText").innerHTML = "This line is written by JavaScript."
}
GLOBAL.myNewFunction = myNewFunction;
})(window.GLOBAL || (window.GLOBAL={}));