如何用javascript捕获“此”返回的html元素(来自DOM)?

时间:2018-09-27 08:44:50

标签: javascript html dom

我正在尝试使用querySelector获取HTML元素,但是它返回null。 我怎么才能得到它?

btn是按钮的“ this”:

<button class="Medium" onclick="restartGame(this, 1)">Medium</button>

我正在尝试的功能是:

function setCurrLevel(btn) {
    var elCurrBtn = document.querySelector(`${btn.class}`);

    if (elCurrBtn.innerText === 'Easy') {
        gCurrLevel = 0; 
    } else if (elCurrBtn.innerText === 'Medium') {
        gCurrLevel = 1; 
    } else if (elCurrBtn.innerText === 'Hard') {
        gCurrLevel = 2; 
    } 

    return gCurrLevel;
}

2 个答案:

答案 0 :(得分:1)

如果btn已经指向该按钮,则根本不需要querySelector。只需使用btn

var gCurrLevel;
function setCurrLevel(btn) {
  if (btn.innerText === 'Easy') {
    gCurrLevel = 0;
  } else if (btn.innerText === 'Medium') {
    gCurrLevel = 1;
  } else if (btn.innerText === 'Hard') {
    gCurrLevel = 2;
  }

  console.log("gCurrLevel = " + gCurrLevel);
  // return gCurrLevel; // Don't do this in an event handler
}
<button class="Medium" onclick="setCurrLevel(this)">Medium</button>

我已将resetGame(this, 1)替换为setCurrLevel(this),以使它们匹配,但可以根据需要进行调整。

答案 1 :(得分:0)

如果将按钮元素传递给setCurrLevel,则无需再选择它

  function setCurrLevel(btn) {
    var gCurrLevel = 0;
    if (btn.innerText === 'Easy') {
        gCurrLevel = 0; 
    } else if (btn.innerText === 'Medium') {
        gCurrLevel = 1; 
    } else if (btn.innerText === 'Hard') {
        gCurrLevel = 2; 
    } 

    return gCurrLevel;
 }