在JavaScript中使用条件

在JavaScript中使用条件,javascript,jquery,Javascript,Jquery,我有这个无限滚动代码,它工作得非常好 我试图在我的代码中使用if-else条件,但由于一些语法错误(我认为)它没有响应出来 我的代码如下: function addrows(rows) { let postList = $("#post-list"); $.each(rows, function (i, row) { var img = row.image; let rowHtml = `

我有这个无限滚动代码,它工作得非常好

我试图在我的代码中使用if-else条件,但由于一些语法错误(我认为)它没有响应出来

我的代码如下:

function addrows(rows) {
        let postList = $("#post-list");
        $.each(rows, function (i, row) {
            var img = row.image;
            let rowHtml = `
                 <div class="mt-3">
             `+if (img == null){ +`
                    <a href="post?id=`+row.id+`" style="color:black;">
                       <p style="font-size: 30px;padding: 15px 30px 15px 30px;">`+row.title+`</p>
                    </a>
             `+} else { +`
                    <a href="post">
                       <img src="images-main/images/`+row.image+`" alt="post-image" class="img-fluid rounded w-100">
                    </a>
              `+}+`
                 </div>
           `;
                        
            postList.append(rowHtml);            

        });
    }
函数addrows(行){
让postList=$(“#post list”);
$.each(行,函数(i,行){
var img=row.image;
让rowHtml=`
`+如果(img==null){+`
`+}否则{+`
`+}+`
`;
append(rowHtml);
});
}
请注意,如果我要删除那些if-else条件,那么整个无限滚动代码工作正常


非常感谢您的帮助。

您不能将if-else与字符串连用,这在javascript中是无效的语法,您可以使用三元条件运算符或类似的if-else

  let postList = $("#post-list");
  $.each(rows, function (i, row) {
    var img = row.image;
    let rowHtml = `<div class="mt-3">`;
    if (img == null) {
      rowHtml += `<a href="post?id=` + row.id + `" style="color:black;">
                      <p style="font-size: 30px;padding: 15px 30px 15px 30px;">`+ row.title + `</p>
                  </a>`;
    }
    else {
      rowHtml += `<a href = "post" >
                      <img src="images-main/images/`+ row.image + `" alt = "post-image" class="img-fluid rounded w-100" >
                  </a>`;
    }
    rowHtml += '< /div>';
    postList.append(rowHtml);
  });
}
let postList=$(“#post list”);
$.each(行,函数(i,行){
var img=row.image;
让rowHtml=`;
如果(img==null){
rowHtml+=`;
}
否则{
rowHtml+=`;
}
rowHtml+='
'; append(rowHtml); }); }
正如您所看到的,您不能将
if..else
内联到字符串串联中

jQuery使DOM元素的创建和操作变得非常简单,所以为什么不使用它呢

函数addrows(行){
$(“#发布列表”).append(rows.map(row=>{
常数a=$(“”)
if(行图像){
a、 追加($(“”){
文本:row.title
}).css({fontSize:“30px”,padding:“15px 30px”}))
}
返回$(“”)。添加类(“mt-3”)。附加(a)
})
}

浏览器开发人员控制台中会出现什么错误?@JaromandaX它说,意外的标记“if”是因为
“str”+if(condition){+“true”+}否则{+“false”+}
远远不是有效的javascript…使用三元运算符…
(condition)?(true时的值):(false时的值)
-对于上述内容,我将使用
()
慷慨地确保您得到正确的result@JaromandaX我用了这个,它说“意外的变量”
var饮料=(年龄>=21岁)?“啤酒”:“果汁”;console.log(饮料);
你把变量放在哪里了?
“字符串”+“另一个字符串”里面
??嘿,你能用同样的代码帮我解决一些其他问题吗?/你能加入这个聊天室,解释那里的情况吗。谢谢兄弟,你能回复聊天室吗?很高兴知道这一点。你会练习这个吗