[英]Why does “you rock” alert always pop up when I click?
I am a new javascript learner. 我是一名新的javascript学习者。 I did this but don't understand why always "you rock" alert pops up when I click.
我这样做了,但不明白为什么当我单击时总是弹出“晃动”警报。 Thanks in advance
提前致谢
function favColors() { var example = document.getElementById('example'); if(document.getElementById('favorite').value=example.options[0].text) { alert("you rock"); }else { alert("have no color taste"); } document.getElementById('favorite').value=example.options[example.selectedIndex].text; }
<form> <select id="example" onChange="favColors()"> <option>Black</option> <option>Red</option> <option>White</option> <option>Pink</option> </select> <p> Your favorite sport is: <input type="text" id="favorite"> </p> </form>
Your IF
clause needs a ==
instead of a single =
. 您的
IF
子句需要==
而不是单个=
。 It should look like this: 它看起来应该像这样:
if(document.getElementById('favorite').value==example.options[0].text) {
instead of 代替
if(document.getElementById('favorite').value=example.options[0].text) {
. if(document.getElementById('favorite').value=example.options[0].text) {
。
Hope it helps. 希望能帮助到你。
Also, this: 另外,这:
document.getElementById('favorite').value=example.options[example.selectedIndex].text;
needs to be the first statement of right after defining example
. 在定义
example
之后,需要首先声明对的权利。
Update: 更新:
example.options[example.selectedIndex].text
needs to be applied to document.getElementById('favorite').value
before you can use it for comparison. example.options[example.selectedIndex].text
应用于document.getElementById('favorite').value
才能进行比较。 =
sign is for assignment and ==
is for comparison. =
符号用于分配,而==
用于比较。 So your IF
statement needed updating accordingly. IF
语句需要相应地更新。 Read this . You're using an assignment instead of a comparison operator inside of your if statement. 您在if语句中使用分配而不是比较运算符。
Assignment operator 赋值运算符
//sets x to 5
x = 5
//sets y to an empty object
y = {}
//sets y to 5
y = x
Regular comparison operator 常规比较运算符
//evaluates to true
5 == 5
//evaluates to true
'5' == '5'
//evaluates to true
'5' == 5
//evaluates to false
'5' == 0
Strict comparison operator (the one you should be using) 严格的比较运算符(您应该使用的运算符)
//evaluates to true
5 === 5
//evaluates to true
'5' === '5'
//evaluates to false
'5' === 5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.