捆绑onclick()函数,使用Event侦听器进行更改

时间:2017-09-29 10:25:39

标签: javascript html css

在下面的html中,有许多onclick()函数,我想将其更改为eventlistner。我是以前使用onlick()的Web编程新手,但是w3标准已经改为事件监听器。任何帮助都非常适合。我想用事件监听器更改onlick()

HTML

<p>
    <button onclick="window.location.reload()">New Game</button>
</p>
<table class="boxes" >
    <tr>
      <td id="0" class="BoxCell" onclick="clickCell(this)">1</td>
      <td id="1" class="BoxCell" onclick="clickCell(this)">2</td>
    </tr>
    <tr>
       <td id="2" class="BoxCell" onclick="clickCell(this)">3</td>
      <td id="3" class="BoxCell" onclick="clickCell(this)">4</td>
    </tr>
    <tr>
      <td id="4" class="BoxCell" onclick="clickCell(this)">5</td>
      <td id="5" class="BoxCell" onclick="clickCell(this)">6</td>
    </tr>
    <tr>
      <td id="6" class="BoxCell" onclick="clickCell(this)">7</td>
      <td id="7" class="BoxCell" onclick="clickCell(this)">8</td>
    </tr>
</table>

JS:

var id_empty;
var num_moves;
var isCompleted = false;
var nums = [1,2,3,4,5,6,7,8];
function startPuzzle() {
num_moves = 0;
isCompleted = false;

for(var i=0; i < 8; i++) {
    var tmp = document.getElementById(i);
    tmp.className = "BoxCell ";
}
randomNumber = nums.sort(function () { return (Math.round(Math.random())-0.5);});
while(!Problem.prototype.is_solvable(randomNumber)) {
    randomNumber = nums.sort(function () { return (Math.round(Math.random())-0.5);});
}
for(var i=0; i < 8; i++) {
    var tmp = document.getElementById(i);
    if(randomNumber[i] == 8) {
        tmp.className = "cell empty";
        tmp.innerHTML = "";
        id_empty = i;
    }
    else
        tmp.innerHTML = randomNumber[i];
  }
 }
function clickCell(x)
{
 if(isCompleted)
    return;

    if(x.id != id_empty+'') {
    var emptyI = Math.floor(id_empty/2);
    var emptyJ = id_empty % 2;
    var id_selected = Number(x.id);
    var selectedI = Math.floor(id_selected/2);
    var selectedJ = id_selected % 2;

    if((Math.abs(emptyI - selectedI) == 1 && emptyJ == selectedJ) ||
       (Math.abs(emptyJ - selectedJ) == 1 && emptyI == selectedI)) {

        document.getElementById(id_empty).className = "BoxCell";
        document.getElementById(id_empty).innerHTML = x.innerHTML;

        x.className = "cell empty";
        x.innerHTML = '';

        id_empty = id_selected;
        num_moves++;

        document.getElementById("moves").innerHTML = "Moves so far: " + num_moves;

        if(isDone()){
            isCompleted = true;
            document.getElementById("moves").innerHTML = "CONGRATS! Number of moves it took to complete: " + num_moves;
        }
    }
}
}

function isDone() {
return document.getElementById('0').innerHTML == '1' &&
    document.getElementById('1').innerHTML == '2' &&
    document.getElementById('2').innerHTML == '3' &&
    document.getElementById('3').innerHTML == '4' &&
    document.getElementById('4').innerHTML == '5' &&
    document.getElementById('5').innerHTML == '6' &&
    document.getElementById('6').innerHTML == '7';
}

function lastClick() {
var curr_state = currentState();
var problem = new Problem(curr_state);
var sol = Solver.a_star_search(problem);
var result = "<ol>";
for(var i = 0; i < sol.length; i++) {
    var n = moveNumb(sol[i],curr_state);
    curr_state = problem.result(sol[i],curr_state);
    result += "<li>move " + n + "</li>";
}
result += "</ol>";
document.getElementById("steps").innerHTML = result;
}

function currentState() {
var result = [];
for(var i = 0; i < 8; i++) {
    var tmp = document.getElementById(String(i)).innerHTML;
    if(tmp == '') {
        result[i] = 8;
    }
    else {
        result[i] = Number(tmp);
    }
  }
  return result;
 }

function moveNumb(action,state) {
var i = state.indexOf(8);
switch(action) {
case Action.up:
    return state[Util.index(Util.x(i),Util.y(i) - 1)];
case Action.down:
    return state[Util.index(Util.x(i),Util.y(i) + 1)];
case Action.right:
    return state[Util.index(Util.x(i) + 1,Util.y(i))];
case Action.left:
    return state[Util.index(Util.x(i) - 1,Util.y(i))];
 }
}

Array.prototype.clone = function() { return this.slice(0); };
Array.prototype.swap = function(i1,i2) {
var copy = this.clone();
var tmp = copy[i1];
copy[i1] = copy[i2];
copy[i2] = tmp;
return copy;
};


var Problem = function(start_state) {
this.init_state = start_state;
return this;
}

Problem.prototype.is_solvable = function(start) {
start = start.clone();
start.splice(start.indexOf(8), 1);
start[7] = 8;
var count = 0;
for(var i = 0; i < 7; i++) {
    if(start[i] != i+1) {
        count++;
        var j = start.indexOf(i+1);
        start[j] = start[i];
        start[i] = i+1;
    }
}
return count % 2 == 0;
}

3 个答案:

答案 0 :(得分:1)

对于单元格部分,您可以将click事件附加到类BoxCell,如:

var box_cell = document.getElementsByClassName("BoxCell");

var clickCell = function() {
  console.log(this.id);
}

for (var i = 0; i < box_cell.length; i++) {
  box_cell[i].addEventListener('click', clickCell, false);
}

按钮可以是:

document.querySelector("#btnReload").addEventListener("click", function(){
    window.location.reload();
});

希望这有帮助。

var box_cell = document.getElementsByClassName("BoxCell");

var clickCell = function() {
  console.log(this.id);
};

for (var i = 0; i < box_cell.length; i++) {
  box_cell[i].addEventListener('click', clickCell, false);
}
<table class="boxes">
  <tr>
    <td id="0" class="BoxCell">1</td>
    <td id="1" class="BoxCell">2</td>
  </tr>
  <tr>
    <td id="2" class="BoxCell">3</td>
    <td id="3" class="BoxCell">4</td>
  </tr>
  <tr>
    <td id="4" class="BoxCell">5</td>
    <td id="5" class="BoxCell">6</td>
  </tr>
  <tr>
    <td id="6" class="BoxCell">7</td>
    <td id="7" class="BoxCell">8</td>
  </tr>
</table>

答案 1 :(得分:1)

我没有完成整个代码,但您可以执行以下操作:

在窗口加载时,您可以遍历td元素并附加click个事件监听器,如:(还包括New Game按钮的点击事件 - 我分配了ID - {{1}到按钮)。

btnReload

您的window.onload = function () { for (i = 0; i <= 7; i++) { document.getElementById(i).addEventListener("click", function (e) { clickCell(e); }) } document.getElementById("btnReload").addEventListener("click", function(){ window.location.reload(); }) } 可以像这样更改:

clickCell

示例:

function clickCell(e) {
    var x = e.target.id;
    console.log(x);

    //reset of your code
}
window.onload = function () {
	for (i = 0; i <= 7; i++) {
		document.getElementById(i).addEventListener("click", function (e) {
			clickCell(e);
		})
	}

	document.getElementById("btnReload").addEventListener("click", function(){
		window.location.reload();
	})
}

function clickCell(e) {
	var x = e.target.id;
	console.log(x);
  //reset of your code
}

答案 2 :(得分:0)

使用jquery on('click',function()); 这在执行方面甚至更好