簡體   English   中英

我如何訪問具有特定 ID 的 div 內部?

[英]How do i have access inside div with specific id?

0 我正在嘗試創建簡單的搖滾、紙、剪刀游戲,但我有一些情況,我想訪問 id 為 firstplayer 的 div,這個 div 也有增量 function,它的值增加 1...如果在形式字段我選擇12,當我按下“firstplayer”時它的值會增加到12,我想console.log(“you win”),我嘗試了很多,但它不起作用,我該怎么辦,解決這個問題? 我不想通過從表單中選擇的值來增加 firstplayer 值,我將數字增加了一個,但是當 firstpalyer 數字值達到表單中標記的標記時,我想 conole log(“you win”)。 例如我在表單字段中選擇了 7,當 firstplayer 數值達到 7 時,我想 conole.log("you win")

 const firsPlayer = document.getElementById("firstplayer"); const Form = document.getElementById("submit"); form.addEventListener("input", function(event){ event.preventDefault(); if (event.target.value==="12"){ //////something } }) var x=0; function increment(){ return firsPlayer.innerHTML = ++x; } function playerwin(){ if(firsPlayer.childNodes[0].nodeValue == 12){ console.log("you win") } }
 <form action="#"> <label for="numbers">Game up to:</label> <select id="form" > <option value="7" >7</option> <option value="12">12</option> <option value="15">15</option> <option value="20">20</option> </select> <input type="submit" id="submit"> </form> <div> <h4 onclick="increment()">Firstplayer</h4> <div id="firstplayer"> </div> </div>

目前尚不清楚您在做什么與“石頭、紙、剪刀”相關,但請參閱下面代碼中的注釋以獲取答案。

 // Get references to the elements you'll work with const btn = document.getElementById("btn"); const sub = document.getElementById("submit"); const firsPlayer = document.getElementById("firstplayer"); const list = document.getElementById("list"); // Set up your event handlers in JavaScript, not HTML btn.addEventListener("click", increment); submit.addEventListener("click", function(event){ if (list.value==="12"){ //////something } }); var x=0; function increment(){ // DIV elements don't have a "value". They "have textContent". // Do you test to see if the player wins right here in the increment function if(++firsPlayer.textContent == list.value){ console.log("you win") } }
 #btn { font-weight:bold; cursor:pointer; margin:1em 0; }
 <,-- Since you aren't submitting data anywhere: you shouldn't use a FORM --> <label for="numbers">Game up to.</label> <select id="list" > <option value="7" >7</option> <option value="12">12</option> <option value="15">15</option> <option value="20">20</option> </select> <input type="button" id="submit" value="Submit"> <div> <.-- You can't have an H4 unless it comes after an H3. Don't use HTML elements because of the way the browser styles them, Use CSS for styling. Also. don't use inline HTML event attributes. Do your event binding in JavaScript. --> <div id="btn">Firstplayer</div> <div id="firstplayer"> </div> </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM