简体   繁体   中英

Use of <img src> in js?

I have the following in place:

    var diff = maxval - ui.value;
    $( "#output").html( diff?"diff. of " + diff : "no diff" ); 

Now I'd like to add an image to each, if there's a difference in value or not, ie:

    var diff = maxval - ui.value;
    $( "#output").html( diff?"<img src='yes.png' height='50' width='50' /> diff. of " + diff : "<img src='no.png' height='50' width='50' /> no diff" ); 

Seeing as though that doesn't work, how can I set an image for each in that output div?

You're checking based on diff , don't you mean to check if it's greater than 0?

Negative numbers evaluate to true .

Boolean(-1);//true
Boolean(50);//true
Boolean(-500);//true
Boolean(-0.001);//true
Boolean(0);//false

Here is how I'd create a new image with a source attribute decided based on diff being greater than 0. Note, I'm using actual elements, so I'm changing the src attribute instead of a string value which I believe creates more readable code.

var diff = maxval - ui.value;
var img = new Image();
img.src = (diff > 0 ) ? "yes.png" : "no.png";
img.width = "50px";
img.height = "50px";
$( "#output").empty().append(img);

Here is a fully vanilla solution, including the text node:

var diff = maxval - ui.value;
var img = new Image();
img.src = (diff > 0 ) ? "yes.png" : "no.png"; // assuming you mean to check positive value
img.width = "50px";
img.height = "50px";
var el = document.getElementById("output");
el.appendChild(img);
var text = (diff > 0) ? "diff" : "no diff";
var txt = document.createTextNode(text);
el.appendChild(txt);

While the advantages of this 'longer' code don't seem obvious at first, it is very easy to manipulate. I'm working with DOM elements directly instead of strings, I can easily add or remove attributes, change properties, clone them, etc.

I am not sure if I understand correctly the question, if so, at least this could guide you a little bit:

var yes = $( "<img>").attr( {"src": 'yes.png', "height": '50', "width": '50' });
var no = $( "<img>").attr( {"src": 'no.png', "height": '50', "width": '50' });

if(diff){
    $( "#output").append(yes).append('diff. of ' + diff);
}
else{
    $( "#output").append(no).append('no diff');
}

Example: http://jsfiddle.net/WKg3A/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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