-1

javascript 関数/変数を非公開にする方法を把握するのに問題があります。このような関数/変数を非公開にするには、これをどのように編集する必要がありますか。

<html>
<head>
<style>
#panel, .flip {
  font-size: 16px;
  padding: 10px;
  text-align: center;
  background-color: #4CAF50;
  color: white;
  border: solid 1px #a6d8a8;
  margin: auto;
}

#panel {
  display: none;
}
</style>
</head>
<body>

<p class="flip" onclick="myFunction()">Click to show panel</p>

<div id="panel">
  <p>This panel contains a div element, which is hidden by default (display: none).</p>
  <p>It is styled with CSS and we use JavaScript to show it (display: block).</p>
  <p>How it works: Notice that the p element with class="flip" has an onclick attribute attached to it. When the user clicks on the p element, a function called myFunction() is executed, which changes the style of the div with id="panel" from display:none (hidden) to display:block (visible).</p>
  <p>You will learn more about JavaScript in our JavaScript Tutorial.</p>
</div>

<script>
function myFunction() {
  document.getElementById("panel").style.display = "block";
}
</script>

</body>
</html>
4

2 に答える 2

0

関数を特定のスコープにラップすることで、関数を「プライベート」にすることができます。

あなたの例では、すぐに呼び出される関数式でラップすることを意味します:

(function () {
  function myFunction() {
    document.getElementById("panel").style.display = "block";
  }

  // myFunction is only available within the outer function context.
})();

これは、以下が機能しなくなることも意味します。

<p class="flip" onclick="myFunction()">Click to show panel</p>

myFunctionは公開されなくなったため、クリックするとエラーがスローされるようになりました。addEventListenerただし、まだ同じスコープにいる場合は、次のように設定できmyFunctionます。

(function () {
  function myFunction() {
    document.getElementById("panel").style.display = "block";
  }

  for(const p of document.querySelectorAll("p.flip")) {
    p.addEventListener("click", myFunction);
  }
})();
于 2020-03-17T22:14:08.373 に答える