jquery Append() 中的 if 语句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12898400/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 12:06:25  来源:igfitidea点击:

If-statement inside jquery Append()

jqueryhtmljsonappend

提问by Solders

Inside my jquery Append() I wan't to run an IF-statement to include an image on all my objects except on the first one.

在我的 jquery Append() 中,我不想运行 IF 语句来在除第一个对象之外的所有对象上包含图像。

Like:

喜欢:

var i = 0;

$('#divDetailsForSelectedInfo').append(
    '<div class="roundedAndBoxShade leftResultObject" id = "' + value.Query.Id + '">'+
    '<div class="leftResultObject_inner">' +
if (i > 0){
   <img src="/img.jpg"/>;
}
'<div>asdf</div>');

The code is generated by Json+Jquery and then it is all appended on a div in my index-file. As far as I've been able to tell through immence google-ing this can't be done, but I might be wrong?

代码由 Json+Jquery 生成,然后全部附加在我的索引文件中的 div 上。据我所知,通过 google-ing 无法完成,但我可能错了?

If it is indeed "impossible", could the :first selector in Jquery be used in some cool way?

如果它确实是“不可能的”,那么 Jquery 中的 :first 选择器可以以某种很酷的方式使用吗?

回答by Kostia

A simpler solution:

一个更简单的解决方案:

var i = 0;
$('#somediv').append(
    'html before' + 
    (i > 0 ? '<img src="/img.jpg"/>': '') +
    'more html'
);

回答by Salil

var i = 0;
var str=''
if (i > 0){
  str =  '<img src="/img.jpg"/>;'
}
$('#divDetailsForSelectedInfo').append(
    '<div class="roundedAndBoxShade leftResultObject" id = "' + value.Query.Id + '">'+
    '<div class="leftResultObject_inner">' +str+'<div>asdf</div>');

回答by David says reinstate Monica

The easiest way I can think of to do this:

我能想到的最简单的方法是:

$('#divDetailsForSelectedInfo').append(
    function(i) {
        return '<div class="roundedAndBoxShade leftResultObject" id = "' + value.Query.Id + '">' + '<div class="leftResultObject_inner">' + (i > 0 ? '<img src="/img.jpg"/>' : '');
    });

JS Fiddle proof-of-concept.

JS Fiddle 概念验证