简体   繁体   English

if声明与img.src

[英]if statement with img.src

The problem: whenever, if i have the single '=' the variable will show up and be fine.. but it completely ignores the if statement. 问题:只要我有单个“ =”,该变量就会显示出来并且很好..但它完全忽略了if语句。 if i only do the double '=='.. the variable doesnt show up, and it goes to the else state. 如果我只做双'=='..变量不显示,它将进入else状态。 lemme know if u see anything wrong. 莱姆知道你是否看错了。

var pic1 = document.getElementById('team1pic').src;
var win1 = document.getElementById('wins').innerHTML;
if (pic1 == 'pens.jpg') {
    document.getElementById('wins').innerHTML = PittWins;
} else {
    document.getElementById('wins').innerHTML = 'no';
}

here is some html to go along with it that i have 这是一些与我一起的HTML

<a class="dock-item" id="pens" href="#" onclick="document.getElementById('team1pic').src='pens.jpg'"><span>Pittsburgh Penguins</span><img src="pens.jpg" alt="Pittsburgh Penguins" /></a>` 

and then 接着

<th width="35%" ><img src="" / id='team1pic'></th>

Do an alert(pic1) before the if and you'll figure it out. if之前执行alert(pic1) ,您会发现它。

The only "problem" is that pic1 is not equal to 'pens.jpg' . 唯一的“问题”是pic1不等于'pens.jpg' If you replace with a single = , the assignment operator, you get an expression that evaluates to 'pens.jpg' , which is always true , so it always runs the first branch. 如果用单个=代替赋值运算符,则会得到一个表达式,其结果为'pens.jpg' ,该表达式始终为true ,因此它始终运行第一个分支。

Better: 更好:

var s = document.getElementById('team1pic').src,
    w = document.getElementById('wins');

w.innerHTML = s == 'pens.jpg' ? PittWins : 'no';

I assume that PittWins is a variable. 我认为PittWins是一个变量。

I would be nice to see the HTML this is attached to. 我很高兴看到它附带的HTML。

The reason the single = works but == doesn't points to the conclusion that they are not equal. 单个=起作用但==的原因并不表明它们不相等的结论。 The reason it shows up for = is because the assignment evaluates to true. 它显示=的原因是因为赋值评估为true。 This will be the case for anything you assign to the variable that is "truthy", meaning the value would evaluate true in JS. 分配给“真实”变量的任何情况都会如此,这意味着该值在JS中将为true。 In javascript everything but 0 , false , null & undefined evaluate to true. 在javascript中,除0falsenullundefined评估为true。

You might want to do an alert(pic1) to see just what is in there, or if you are using Firefox or Chrome you can use the Javascript debugger tools. 您可能需要执行alert(pic1)以查看其中的内容,或者如果使用的是Firefox或Chrome,则可以使用Javascript调试器工具。

use 采用

var pic1 = document.getElementById('team1pic').getAttribute('src',2);

...to get the src like it's defined and not the complete path. ...以获得定义的src,而不是完整的路径。

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

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