Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
247 views
in Technique[技术] by (71.8m points)

javascript - How to display different image depends on td value?

I am using wordpress and would like to build a page with shipment trackin similar function.

i.e. if a package is delivered and that delivery result cell is not empty, then show colored image, otherwise show grey image.

my delivery result cell has the id "f1" and is empty

<td id="f1"><td>

After that i tried following code without success

<script>
var x = document.getElementById ( "f1" );
if (x == null){
document.write('<img src="/wp-content/uploads/2021/01/airplane_off.png" style="width: 512px; height: 512px; margin: 1px;" />');
}
else{
document.write('<img src="/wp-content/uploads/2021/01/airplane_on.png" style="width: 512px; height: 512px; margin: 1px;" />');
}
</script>

Your help is appreciated


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If I understand correctly, you're looking to see if the inner html is empty.

You should be able to tell if the content is blank using innerHTML:

var x = document.getElementById("f1");

if (x && x.innerHTML.trim() == ""){
  document.write('<img src="/wp-content/uploads/2021/01/airplane_off.png" style="width: 512px; height: 512px; margin: 1px;" />');
}
else{
  document.write('<img src="/wp-content/uploads/2021/01/airplane_on.png" style="width: 512px; height: 512px; margin: 1px;" />');
}

Note that your example uses <td id="f1"><td>. The tag is not being closed, which will cause issues if you have that in the page too.

The other thing to note is that td needs to be in a proper table structure (meaning inside a tr which needs to be inside a table) otherwise you won't be able to target it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...