繁体   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