javascript - 在 JavaScript 中使用条件

标签 javascript jquery

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

我试图在我的代码中使用 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/

相关文章:

javascript - JQuery 使用传递的参数值通过 $(document).ready 初始化页面

jquery - Jssor slider : How to target specific slide with text/image link?

javascript - 嵌套模型通过javascript添加和销毁

jquery - jQuery 中的取消绑定(bind)/绑定(bind)与委托(delegate) : Which is the best solution?

jquery - 如何从 ul li 列表中的链接获取 href 值

javascript - 在 Angular Directive(指令)上提交表单之前更改输入值

javascript - 如何删除 json 响应中的特定键

javascript - 更新 td 的值而不需要重新加载页面

javascript - 使用 node.js child_process 调用 python 脚本

javascript - 切换菜单 - 使菜单在当前页面保持打开状态