我有这个无限滚动代码,它工作得很好。
我试图在我的代码中使用 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);
});
}
请注意,如果我要删除这些 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);
});
}
关于javascript - 在 JavaScript 中使用条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64566937/