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

时间:2018-11-10 11:12:50

标签: javascript html onclick getelementbyid

民间 我是一个完全菜鸟,所以我敢肯定,这将是一个非常基本的问题,对不起。

我有一个javascript文件,该文件链接到包含许多按钮的html文件。一个这样的按钮的onclick事件似乎完全绕过了onlick事件,并在页面打开后立即触发。有任何想法吗?不好意思地问,什么可能是最基本的东西,但是我已经失去了花在试图使它仅在“ click”事件上起作用的时间。...

在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>

1 个答案:

答案 0 :(得分:1)

解决方案:

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

没有注册eventListener,而是执行sortByName函数。 您需要在此处关闭,如下所示:

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

一些评论:

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

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