在js中使用<img rel="nofollow noreferrer" src>?

Dav*_*ave 4 javascript jquery jquery-ui image

我有以下内容:

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

现在我想为每个添加一个图像,如果价值有差异,即:

    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" ); 
Run Code Online (Sandbox Code Playgroud)

看起来好像不起作用,如何在输出div中为每个设置图像?

Ben*_*aum 6

你正在检查diff,不是要检查它是否大于0?

负数评估为true.

Boolean(-1);//true
Boolean(50);//true
Boolean(-500);//true
Boolean(-0.001);//true
Boolean(0);//false
Run Code Online (Sandbox Code Playgroud)

这是我如何使用基于diff大于0的源属性创建一个新图像.注意,我正在使用实际元素,所以我正在更改src属性而不是字符串值,我认为它更易读码.

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);
Run Code Online (Sandbox Code Playgroud)

这是一个完全香草的解决方案,包括文本节点:

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);
Run Code Online (Sandbox Code Playgroud)

虽然这种"更长"代码的优点起初并不明显,但它很容易操作.我直接使用DOM元素而不是字符串,我可以轻松添加或删除属性,更改属性,克隆它们等.