JavaScript DOM-その要素が作成された後、document.createElementで作成された変数にアクセスしますか?

キャプテンセンシブル

関数内でdocument.createElementを使用してdiv(変数「ボックス」)を作成しました。次に、その変数を他の関数内で使用する必要があります。関数の外部でこの変数にアクセスしたり、作成後にグローバルに割り当てることはできますか?

私のコードは3つのことをすることになっています(Odinプロジェクトのエッチ・ア・スケッチ・プロジェクトです)。

  • 16x16ボックスのグリッドを生成します。
  • ユーザーがいくつかのボックスを入力し、ユーザーの入力に基づいて新しいグリッドを作成できるようにします。
  • mouseOverで、ボックスの色をさまざまな方法で操作します(「黒」、「色」、「サイク」のラベルが付いています)。

私が試したこと(しかし失敗したこと)。

  • すべての関数を「initGrid」関数内に配置します。これにより、ボタンのeventListenersも内部に移動する必要があり、ボタンが機能しなくなりました。

  • container.childNodesを使用して、作成されたノードの後に​​変数を割り当てようとします。

  • 別の「letbox = document.createElement( "div");」を追加する 変数にグローバルに名前を付けようとして、変数の外側。

  • 他にいくつ試したかわからないので、数え切れません。

この時点で私が機能させようとしているボタン機能は「色」オプションだけであることに注意してください。私は他の人が働いていますが、それらは他のhtmlファイルにあります。

どんな助けも素晴らしいでしょう、私はそれで迷子になります。何か明確にできるかどうか教えてください。

* {
	padding: 0;
	margin: 0;
}

header {
	text-align: center;
	background-color: maroon;
	padding:10px;
	margin: 10px 10px 20px 10px;
}

.title {
	font-family: sans-serif;
	font-size: 50px;
	color: white;
}

#wrapper{
	text-align: center;
	margin: 0px 0px 15px 0px;
}

#btn{
	color:red;
}

#container{
	margin:0 auto;
	display: flex;
    justify-content: center;
    flex-wrap: wrap;
	max-width:700px;
	max-height:700px;
	min-width: 700px;
	min-height: 700px;
	padding:10px;
	border:1px solid black;
}

.boxes{
	background-color: red;
	border: 0.125px solid white;
	box-sizing: border-box;
}
<!DOCTYPE html>
<html>

<head>
	<title>sketch</title>
	<link href="style.css" rel="stylesheet" type="text/css">
</head>

<body>
	<header>
		<h1 class="title">Etch-A-Sketch</h1>
	</header>
	<div id="wrapper">
		<button id="btn">Reset Grid</button>
    </div>
  	<div id=btns>
  		<button id="black">Paint it Black</button>
  		<button id="color">Rainbow</button>
  		<button id="psych">Psychedelic Disco</button>
  	</div>
	<div id="container">
	</div>
	<div id="prompt">
	</div>


	<script type="text/javascript">
		const container = document.getElementById("container");
		const rstbtn = document.getElementById("btn");
		const btns = document.getElementById("btns");
		const black = document.getElementById("black");
		const color = document.getElementById("color");
		const psych = document.getElementById("psych");
		let box = document.createElement("div");

		black.addEventListener("click",function(){
			option("black");
		});
		color.addEventListener("click",function(){
			option("color");
		});
		psych.addEventListener("click",function(){
			option("psych");
		});	


		initGrid(16);

		function initGrid(num){
			for (let i=0; i<num; i++){
				for (let j=0; j<num; j++){

					let box = document.createElement("div");
         			let boxSize = (690/num) + "px";
         			box.style.height = boxSize;
         			box.style.width = boxSize;
					box.classList.add("boxes");
					container.appendChild(box);

					box.addEventListener ("mouseover",function(){
					console.log("hover, hover, hover, hover");
					});
				}
			}	
		};


			function option(input){
				if (input == "color"){
					console.log("color picked is " + rainbow())
					box.style.backgroundColor = rainbow()
				}else if (input == "psych"){
					console.log("psych")
				}else{
					console.log("black")
				}
			};


		rstbtn.addEventListener("click", function(){
			let newNum = window.prompt ("Enter how many tiles you would like the new grid to be.", "16");
			container.innerHTML="";
			initGrid(newNum);

		});


		//color function
		function rainbow() {
			let randomNum = Math.floor(Math.random() * 10);
			if (randomNum == 0){
				return "yellow";
			}else if(randomNum == 1){
				return "orange";
			}else if(randomNum == 2){
				return "red";
			}else if(randomNum == 3){
				return "maroon";
			}else if(randomNum == 4){
				return "blue";
			}else if(randomNum == 5){
				return "indigo";
			}else if(randomNum == 6){
				return "pink";
			}else if(randomNum == 7){
				return "purple";
			}else if(randomNum == 8){
				return "green";
			}else if(randomNum == 9){
				return "lime";
			}else{
				return "black";
			}
		};
 		
	</script>
			

</body>

</html>

cнŝdk

問題:

実際の問題はbox、1つはグローバルに、もう1つは関数内で2回宣言しているため、最初の宣言は関数内にあるために引き上げられることです。

実際のコードでlet box = document.createElement("div");は、関数から削除するだけで、関数内のグローバル変数としてアクセスされます。

デモ:

これが最終的なコードのあり方です。

const container = document.getElementById("container");
const rstbtn = document.getElementById("btn");
const btns = document.getElementById("btns");
const black = document.getElementById("black");
const color = document.getElementById("color");
const psych = document.getElementById("psych");
let box = document.createElement("div");

black.addEventListener("click", function() {
  option("black");
});
color.addEventListener("click", function() {
  option("color");
});
psych.addEventListener("click", function() {
  option("psych");
});


initGrid(16);

function initGrid(num) {
  for (let i = 0; i < num; i++) {
    for (let j = 0; j < num; j++) {

      let boxSize = (690 / num) + "px";
      box.style.height = boxSize;
      box.style.width = boxSize;
      box.classList.add("boxes");
      container.appendChild(box);

      box.addEventListener("mouseover", function() {
        console.log("hover, hover, hover, hover");
      });
    }
  }
};


function option(input) {
  if (input == "color") {
    console.log("color picked is " + rainbow())
    box.style.backgroundColor = rainbow()
  } else if (input == "psych") {
    console.log("psych")
  } else {
    console.log("black")
  }
};


rstbtn.addEventListener("click", function() {
  let newNum = window.prompt("Enter how many tiles you would like the new grid to be.", "16");
  container.innerHTML = "";
  initGrid(newNum);

});


//color function
function rainbow() {
  let randomNum = Math.floor(Math.random() * 10);
  if (randomNum == 0) {
    return "yellow";
  } else if (randomNum == 1) {
    return "orange";
  } else if (randomNum == 2) {
    return "red";
  } else if (randomNum == 3) {
    return "maroon";
  } else if (randomNum == 4) {
    return "blue";
  } else if (randomNum == 5) {
    return "indigo";
  } else if (randomNum == 6) {
    return "pink";
  } else if (randomNum == 7) {
    return "purple";
  } else if (randomNum == 8) {
    return "green";
  } else if (randomNum == 9) {
    return "lime";
  } else {
    return "black";
  }
};


関数の外部でこの変数にアクセスしたり、作成後にグローバルに割り当てることはできますか?

はい、もちろん可能です。実際、との間には大きな違いがdeclarationありinitializationます。必要なのは、関数の外部でグローバルに宣言し、関数で初期化することです。

次のようにグローバルに宣言します。

let box;

次に、関数内で初期化します

box = document.createElement("div");

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

Related 関連記事

ホットタグ

アーカイブ