简体   繁体   English

单击按钮时的Javascript检查输入是否与随机选择的字符串中的char匹配,并将图像更改为该字母

[英]Javascript when button is clicked checks if the input matches a char in a random selected string and change the image to that letter

So I have my code so far producing the images and selecting a random word from an array list and producing the right number of images for characters in my random chosen word. 因此,到目前为止,我的代码都生成图像并从数组列表中选择一个随机单词,并为随机选择的单词中的字符生成正确数量的图像。 My issue is that how do I check the exact input from a textbox when a button is clicked to see if the letter in the textbox is in the string and if so replace the correct image with the letter. 我的问题是,当单击按钮以查看文本框中的字母是否在字符串中时,如何检查文本框中的确切输入,如果是,则用字母替换正确的图像。 If not have the letter show up to the side showing that is was already guessed. 如果没有字母出现在表明已经猜到的那面。

 function change(){ check(); } function check(){ var a = document.getElementById("input").value; var num = Math.floor(Math.random() * 4); var words = ["cat", "dog", "fish", "bird"]; var select = words[num]; var low = select.toLowerCase(); alert(select); for(var b = 0; b < select.length; b++){ var element = document.getElementById("main"); var img = document.createElement("IMG"); img.setAttribute("src", "https://vignette.wikia.nocookie.net/yugioh/images/e/e5/Back-EN.png/revision/latest?cb=20100726082133"); element.appendChild(img); } for(var i = 0; i < low.length; i++){ if(low.charAt(i) != low){ var para = document.createElement("P"); var node = document.createTextNode(a + " "); para.appendChild(node); var element = document.getElementById("main"); element.appendChild(para); } else if(low.charAt(i) == low){ var element = document.getElementById("main"); img.setAttribute("src", "a"); element.appendChild(img); } } } 
 img{ width: 100px; } 
 <body onload='change()'> <script src="index.js"></script> <div id="main"> <input type="text" placeholder="Guess" id="input"> <button onclick='clickCheck()'>Click</button> </div> </body> 

I do not want any jquery. 我不要任何jQuery的。

If you want to do this using the Javascript then you can do it like this 如果您想使用Java脚本执行此操作,则可以这样做

<button id="abc" onClick="myFunction()">Click</button>

<script>
function myFunction() {
    //your code here to do what you want to
}
</script>

or 要么

<script>
document.getElementById("#abc").addEventListener("click", function(){
//your code here
}); 
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM