Can you explain how to make the javascript alert appear after radio button has been shown where the user clicked?

huangapple go评论69阅读模式
英文:

Can you explain how to make the javascript alert appear after radio button has been shown where the user clicked?

问题

我尝试过这样做,但它会在显示用户点击单选按钮之前显示警报。我应该从函数中删除switch语句吗?希望我能解决这个问题,因为在其他网站上似乎可以工作。

<!DOCTYPE html>
<html lang="en">
  <head>
    <title> colors </title>
    <!-- 在这里添加用于引用包含事件处理程序函数的Javascript文件的script标签 -->
    <script type="text/javascript" src="colors.js">
    </script>
  </head>
  <body>
    <h4> 选择你喜欢的颜色 </h4>
    <form id="colorsForm">
      <label>输入你的名字:
        <input type="text" name="nameTextBox" id="nameBox" /> <br/>
      </label>
      <label> <input type="radio" name="colorButton"
                     value="red" id="red" />
        红色 </label>
      <br />
      <label>  <input type="radio" name="colorButton"
                      value="blue" id="blue" />
        蓝色 </label>
      <br />
      <label> <input type="radio" name="colorButton"
                     value="green" id="green" />
        绿色 </label>
      <br />
      <label> <input type="radio" name="colorButton"
                     value="yellow" id="yellow" />
        黄色 </label>
      <br />
      <label> <input type="radio" name="colorButton"
                     value="orange" id="orange" />
        橙色 </label>
    </form>
  </body>
</html>
英文:

I have tried doing this, but it would display alert before showing what the user clicked for the radio button...
Should I remove the switch statement from the function?
Hopefully I can get this fixed because it seems like it works in other websites.
Ignore text in this sentence here because the post requires more 'detail' apparently.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

&quot;use strict&quot;;
window.onload = pageLoad;

function pageLoad(){
	var redButton = document.getElementById(&quot;red&quot;).onclick=colorChoice;
	var blueButton = document.getElementById(&quot;blue&quot;).onclick=colorChoice;
	var greenButton = document.getElementById(&quot;green&quot;).onclick=colorChoice;
	var yellowButton = document.getElementById(&quot;yellow&quot;).onclick=colorChoice;
	var orangeButton = document.getElementById(&quot;orange&quot;).onclick=colorChoice;
}

function colorChoice(){
	var userName = document.getElementById(&quot;nameBox&quot;).value;
	var color;
	var all_colors = document.getElementsByName(&quot;colorButton&quot;);
	for(var i = 0; i &lt; all_colors.length; i++){
		if(all_colors[i].checked){
			color = all_colors[i].value;
		}
	}
	switch (color){
		case &quot;red&quot;:
		alert(&quot;Hi &quot; + userName + &quot;, your favorite color is red&quot;);
		break;
		case &quot;blue&quot;:
		alert(&quot;Hi &quot; + userName + &quot;, your favorite color is blue&quot;);
		break;
		case &quot;green&quot;:
		alert(&quot;Hi &quot; + userName + &quot;, your favorite color is green&quot;);
		break;
		case &quot;yellow&quot;:
		alert(&quot;Hi &quot; + userName + &quot;, your favorite color is yellow&quot;);
		break;
		case &quot;orange&quot;:
		alert(&quot;Hi &quot; + userName + &quot;, your favorite color is orange&quot;);
		break;
		default:
		alert(&quot;There is an error&quot;);
		break;
	}
}

<!-- language: lang-html -->

&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
  &lt;head&gt;
    &lt;title&gt; colors &lt;/title&gt;
    &lt;!-- add here the script tag to reference the Javascript file that will contain your event handler function --&gt;
	
		&lt;script type = &quot;text/javascript&quot;  src = &quot;colors.js&quot; &gt;
  &lt;/script&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;h4&gt; Choose your favorite color &lt;/h4&gt;
    &lt;form id=&quot;colorsForm&quot;&gt;
      &lt;label&gt;Enter your name: 
       &lt;input type = &quot;text&quot;  name = &quot;nameTextBox&quot; id=&quot;nameBox&quot; /&gt; &lt;br/&gt;
      &lt;/label&gt;
      &lt;label&gt; &lt;input type = &quot;radio&quot;  name = &quot;colorButton&quot;  
                     value = &quot;red&quot; id=&quot;red&quot; /&gt; 
        Red &lt;/label&gt;
      &lt;br /&gt;
      &lt;label&gt;  &lt;input type = &quot;radio&quot;  name = &quot;colorButton&quot;  
                      value = &quot;blue&quot; id=&quot;blue&quot; /&gt; 
        Blue &lt;/label&gt;
      &lt;br /&gt;
      &lt;label&gt; &lt;input type = &quot;radio&quot;  name = &quot;colorButton&quot;  
                     value = &quot;green&quot; id=&quot;green&quot; /&gt;      
         Green &lt;/label&gt;
      &lt;br /&gt;
      &lt;label&gt; &lt;input type = &quot;radio&quot;  name = &quot;colorButton&quot;  
                     value = &quot;yellow&quot; id=&quot;yellow&quot; /&gt;
         Yellow &lt;/label&gt;
      &lt;br /&gt;
      &lt;label&gt; &lt;input type = &quot;radio&quot;  name = &quot;colorButton&quot;  
                     value = &quot;orange&quot; id=&quot;orange&quot; /&gt;
         Orange &lt;/label&gt;
    &lt;/form&gt;
	&lt;/body&gt;
&lt;/html&gt;

<!-- end snippet -->

答案1

得分: 0

我认为应该删除switch语句。

如果alert阻止了窗口渲染,请尝试添加一个计时器来解决这个问题。

英文:

I think the switch should be removed

If alert blocks window rendering, try adding a timer to solve the problem

&#39;use strict&#39;
window.onload = pageLoad
const colors = [&#39;red&#39;, &#39;blue&#39;, &#39;green&#39;, &#39;yellow&#39;, &#39;orange&#39;]
function pageLoad() {
	colors.forEach(function (color) {
		document.getElementById(color).onchange = colorChoice
	})
}
function colorChoice() {
	var userName = document.getElementById(&#39;nameBox&#39;).value
	var color
	var all_colors = document.getElementsByName(&#39;colorButton&#39;)
	for (var i = 0; i &lt; all_colors.length; i++) {
		if (all_colors[i].checked) {
			color = all_colors[i].value
		}
	}
	setTimeout(() =&gt; {
		if (colors.includes(color)) {
			alert(&#39;Hi &#39; + userName + &#39;, your favorite color is &#39; + color)
		} else {
			alert(&#39;There is an error&#39;)
		}
	}, 10)
}

答案2

得分: 0

这是你提供的内容的翻译:

有几个问题在这里。你不能先点击单选按钮以反映其已被选中,然后再运行你的操作,即alert。通常情况下,这样的方法是不需要的,因为在大多数情况下,应用程序允许用户在表单上做出所有必要的选择,然后要求点击某种submit按钮来处理所有的选择。

这里的另一个问题是alert函数会阻塞JS代码的执行,由于JS是同步和单线程的语言,单选按钮会等待事件完成,然后才更新其外观并在视觉上选中。alert在生产环境中几乎不被使用,因为它无法样式化,而且是阻塞的,在大多数情况下是不希望的。

因此,如果你想坚持你的方法,克服阻塞行为的最佳选项是使用setTimeout来延迟alert,如下所示:

setTimeout(() => alert("Hi " + userName + ", your favorite color is red"), 100);

100毫秒足够让单选按钮在显示警告之前更新。

我不建议在生产环境中使用这种方法,而是选择使用基于HTML/CSS/JS的弹出窗口。有很多教程(例如,这个)和JS库/框架可以帮助你实现这一点。

但是,如果你想用更少的JS代码实现相同的结果,可以看看这个选项:

<!-- 在此处添加引用包含事件处理程序函数的JavaScript文件的脚本标记 -->
<script type="text/javascript" src="colors.js"></script>

<h4>选择你喜欢的颜色</h4>
<form id="colorsForm">
  <label>输入你的名字:
    <input type="text" name="nameTextBox" id="nameBox" /><br/>
  </label>
  <label><input type="radio" name="colorButton" value="red" id="red" />红色</label><br />
  <label><input type="radio" name="colorButton" value="blue" id="blue" />蓝色</label><br />
  <label><input type="radio" name="colorButton" value="green" id="green" />绿色</label><br />
  <label><input type="radio" name="colorButton" value="yellow" id="yellow" />黄色</label><br />
  <label><input type="radio" name="colorButton" value="orange" id="orange" />橙色</label>
</form>

希望这能帮助你理解代码和内容的翻译。

英文:

There are a few things here. You cannot make the radio button process click first (to reflect that it is selected) and only then run your action which is alert. Usually, such an approach is not needed because, in most cases, apps allow users to make all necessary choices on a form and then ask to click some kind of submit button to process all the selections.

Another problem here is that the alert function is blocking JS code execution, and since JS is synchronous and single-threaded language, the radio button waits for the event to finish before it updates its look and becomes visually selected. alert is almost never used in a production environment because it cannot be styled and it is blocking, which is undesired in most cases.

Therefore, if you want to stick to your approach, the best option to overcome blocking behavior is to delay alert with setTimeout, like so:

setTimeout(() =&gt; alert(&quot;Hi &quot; + userName + &quot;, your favorite color is red&quot;), 100);

100 msec will be enough for the radio button to update before the alert is shown.

I wouldn't recommend using this approach on production and go with a HTML/CSS/JS based popup. There are plenty of tutorials (for example, this one) and JS libs/frameworks helping with this.

However, if you are wondering how to achieve the same result with significantly less JS code, take a look at this option:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const userNameInput = document.querySelector(&#39;#nameBox&#39;);
const colorInputs = Array.from(document.querySelectorAll(&#39;input[name=&quot;colorButton&quot;]&#39;));

const clickHandler = (event) =&gt; {
  setTimeout(() =&gt; {
    alert(`Hi ${userNameInput.value}, your favorite color is ${event.target.value}`);
  }, 100);
};

colorInputs.forEach((input) =&gt; input.addEventListener(&#39;click&#39;, clickHandler));

<!-- language: lang-html -->

&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
  &lt;head&gt;
    &lt;title&gt; colors &lt;/title&gt;
    &lt;!-- add here the script tag to reference the Javascript file that will contain your event handler function --&gt;
	
		&lt;script type = &quot;text/javascript&quot;  src = &quot;colors.js&quot; &gt;
  &lt;/script&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;h4&gt; Choose your favorite color &lt;/h4&gt;
    &lt;form id=&quot;colorsForm&quot;&gt;
      &lt;label&gt;Enter your name: 
       &lt;input type = &quot;text&quot;  name = &quot;nameTextBox&quot; id=&quot;nameBox&quot; /&gt; &lt;br/&gt;
      &lt;/label&gt;
      &lt;label&gt; &lt;input type = &quot;radio&quot;  name = &quot;colorButton&quot;  
                     value = &quot;red&quot; id=&quot;red&quot; /&gt; 
        Red &lt;/label&gt;
      &lt;br /&gt;
      &lt;label&gt;  &lt;input type = &quot;radio&quot;  name = &quot;colorButton&quot;  
                      value = &quot;blue&quot; id=&quot;blue&quot; /&gt; 
        Blue &lt;/label&gt;
      &lt;br /&gt;
      &lt;label&gt; &lt;input type = &quot;radio&quot;  name = &quot;colorButton&quot;  
                     value = &quot;green&quot; id=&quot;green&quot; /&gt;      
         Green &lt;/label&gt;
      &lt;br /&gt;
      &lt;label&gt; &lt;input type = &quot;radio&quot;  name = &quot;colorButton&quot;  
                     value = &quot;yellow&quot; id=&quot;yellow&quot; /&gt;
         Yellow &lt;/label&gt;
      &lt;br /&gt;
      &lt;label&gt; &lt;input type = &quot;radio&quot;  name = &quot;colorButton&quot;  
                     value = &quot;orange&quot; id=&quot;orange&quot; /&gt;
         Orange &lt;/label&gt;
    &lt;/form&gt;
	&lt;/body&gt;
&lt;/html&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年5月30日 08:49:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76361003.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定