javascript - 捆绑 onclick() 函数,使用事件监听器更改

标签 javascript html css

在下面的html中,有很多onclick()函数,我想把它改成eventlistner。我是网络编程的新手,之前使用过 onlick(),但 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;
}

最佳答案

对于单元格部分,您可以将点击事件附加到 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>

关于javascript - 捆绑 onclick() 函数,使用事件监听器更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46486860/

相关文章:

jQuery - 将具有颜色属性的类添加到链接

javascript - 如何将javascript的变量值传递给jsp中的java字符串

css - float 列表项导致元素符号/数字在 webkit 上消失

html - CSS Ease-in-out 到全屏

html - 如何在 Bootstrap 的页面中心对齐文本和矩形(带有一些文本)?

html - 奇怪的 IE 错误?

javascript - 我的 jquery 中的顶部圆 Angular

javascript - 使用 Backbone.js 时是否必须使用后端?

javascript - 我如何在日期选择器中隐藏过去的日期

javascript - 解析Webview的HTML内容-Android