【发布时间】:2019-02-03 11:54:59
【问题描述】:
我想要实现的是有 1 个问题和 4 个可能的答案可供选择(单选按钮)。当用户在表单后按下按钮时,我想要一个段落来告诉他们更多关于他们所做的选择。
我已经在我的 JavaScript 中定位了按钮、段落和单选按钮。每当我选择第一个单选按钮时,我还设法使段落文本出现。但是,如果同时选择了一个单选按钮并且按下了该按钮,我只希望段落中的文本出现。我希望段落中出现不同的内容,具体取决于选择的单选按钮。
任何提示或解决方案将不胜感激 =)
到目前为止,这是我的代码:
<form action="">
<h1>A friend invites you to a party. You...</h1>
<br />
<input id="red" type="radio" name="color" value="red">...bluntly tell your friend you have other priorities. <br/>
<input id="blue" type="radio" name="color" value="blue">...tell your friend you are finishing a coding assignment tonight. <br/>
<input id="yellow" type="radio" name="color" value="yellow">...hug your friend and start discussing the outfit. <br/>
<input id="green" type="radio" name="color" value="green">...thank your friend for inviting you, and tell her you look forward to it. <br/>
</form>
<button> Click me </button>
<p></p>
<script>
let btn = document.querySelector('button');
let para = document.querySelector('p');
let response = document.querySelector('input');
response.addEventListener('change', myColor);
function myColor() {
let choice = response.value;
if (choice === 'red') {
para.textContent = 'You´re so red!';
} else if (choice === 'blue') {
para.textContent = 'You´re so blue!';
} else if (choice === 'yellow') {
para.textContent = 'You´re so yellow!';
} else if (choice === 'green') {
para.textContent = 'You´re so green!';
}
}
</script>
【问题讨论】:
-
我有点困惑。您只希望在按下“单击我”时出现相关文本?然后,您需要将您的函数附加到按钮上的
click事件 - 而不是像现在这样,附加到无线电输入上的change事件。 -
嗨罗宾,你是对的。我应该更清楚地说明这一点。
标签: javascript html radio-button paragraph