gpt4 book ai didi

javascript - onclick 事件发生而没有实际发生 click 事件 - js

转载 作者:行者123 更新时间:2023-11-30 20:02:24 25 4
gpt4 key购买 nike

伙计们我是一个完全的新手,所以对于这将是一个非常基本的问题,我深表歉意,我敢肯定。

我有一个 javascript 文件链接到一个包含许多按钮的 html 文件。一个这样的按钮的 onclick 事件似乎完全绕过 onlick 事件并在页面打开时立即触发。有任何想法吗?很抱歉问什么可能是真正基本的东西,但我已经忘记了我花了多少时间试图让它只在“点击”事件上工作....

在Java中:

var arrEnrolments=[];//global array
function init() {
populateEnrolments();
var enrolArray=arrEnrolments

document.getElementById("resetEnrol").onclick=resetEnrolments;
document.getElementById("listEnrol").onclick=listAllEnrols;
document.getElementById("sortEnrol").onclick=sortByName(arrEnrolments);
}

function populateEnrolments(){
arrEnrolments=[];
var stuOne={id:1234567, name: "Jones, Brigit", mark: null, grade: ""};
var stuTwo={id:1234566, name: "Somers, Tom ", mark: null, grade: ""};
var stuThree={id:1222445, name: "Lee, Vera", mark: null, grade: ""};
var stuFour={id:1220123, name: "Crawford, Anne", mark: null, grade: ""};
var stuFive={id:1244444, name: "Wu, Russel", mark: null, grade: ""};
var stuSix={id:1238899, name: "Shaw, Boris", mark: null, grade: ""};
var stuSeven={id:1237799, name: "Wilson, Terri", mark: null, grade: ""};
arrEnrolments=[stuOne, stuTwo, stuThree, stuFour, stuFive, stuSix, stuSeven];
}

function sortByName(searchArray) {

var pos=0;
var count, temp;

do{
var msgOut="Student records sorted into Name ascending sequence";
count=0;
for(var pos=0; pos<searchArray.length-1; pos++){
if(searchArray[pos].name>searchArray[pos+1].name){
temp=searchArray[pos];
searchArray[pos]=searchArray[pos+1];
searchArray[pos+1]=temp;
count++
}//end if
}//end for
} while (count>0)//end do

addToOutput(msgOut);
}

function addToOutput(output){
var msgOut=output;
document.getElementById("output").innerHTML=msgOut;

}

window.onload = init;

在 html 中:

<body>
<header>
<h1>Tracking Student Enrolments and Completions<h1>
</header>
<article class="flex-container">
<section class="flex-item">
<h2>Enrolments</h2>
<button type="button" id="resetEnrol">Reset Enrolment List</button>
<button type="button" id="listEnrol">List All Enrolments</button>
<button type="button" id="sortEnrol">Sort Enrolments by Name</button><br/>
</article>
</body>

最佳答案

解决方法:

document.getElementById('sortEnrol').onclick = sortByName(arrEnrolments);

没有注册 eventListener 而是执行 sortByName 函数。你需要一个闭包如下:

document.getElementById('sortEnrol').onclick = function () {
sortByName(arrEnrolments);
};

一些评论:

  • enrolArray 变量在 init 函数中创建但从未使用过

  • pos 变量在 sortByName 函数中定义了两次

关于javascript - onclick 事件发生而没有实际发生 click 事件 - js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53238367/

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