jQuery使用if条件追加div

use*_*331 0 jquery

我有这个附加声明

$("#questions").append($("<tr><td>" + if(value.NA == true) { + "<input type='checkbox' id='" + value.Question_ID + "-na' class='na' /> " + } + "</td>");
Run Code Online (Sandbox Code Playgroud)

我正在尝试向追加添加条件,但是我收到此错误:

Uncaught SyntaxError: Unexpected token if
Run Code Online (Sandbox Code Playgroud)

我假设这是非法的,什么是完成我想要完成的最好的方法?

Tus*_*har 5

if 不能在字符串中使用.

使用变量来存储HTML并使用变量append.

var input = ''; // Set as empty string

if(value.NA === true) {
    input = "<input type='checkbox' id='" + value.Question_ID + "-na' class='na' /> ";
}

$("#questions").append($("<tr><td>" + input + "</td>"));
Run Code Online (Sandbox Code Playgroud)

?..:也可以使用三元运算符()

$("#questions").append($("<tr><td>" + (value.NA ? "<input type='checkbox' id='" + value.Question_ID + "-na' class='na' /> " : '') + "</td>"));
Run Code Online (Sandbox Code Playgroud)