我正在以这种方式形成HTML
divhtml.append('<section class="cartTable"> \
<table width="50%" border="0" cellspacing="0" cellpadding="0" class="totalWrap" align="right"> \
<tbody> \
<tr><td align="right" valign="middle" width="50%">Services Charges</td> \
<td align="right" valign="middle" width="50%">Rs. '+servicecharge+'</td> \
</tr> \
<tr><td align="right" valign="middle">Sur Charges</td> \
<td align="right" valign="middle">Rs. '+surcharge+'</td> \
</tr> \
<tr style="border:none;"><td align="right" valign="middle">VAT</td> \
<td align="right" valign="middle"><strong>Rs. '+VAT+'</strong></td> \
</tr><tr style="border:none;"><td align="right" valign="middle">Sub Total</td> \
<td align="right" valign="middle"><strong>Rs. '+subtotal+'</strong></td> \
</tr> \
</tbody> \
</table> \
<br><br><br> \
</section>');
是否可以在形成HTML
中设置条件if(something >=0)
{
<tr><td align="right" valign="middle">Sur Charges</td> \
<td align="right" valign="middle">Rs. '+surcharge+'</td> \
</tr> \
}
意味着我想只打印一次。
答案 0 :(得分:2)
试试这个:
var html = '<section class="cartTable">
<table width="50%" border="0" cellspacing="0" cellpadding="0" class="totalWrap" align="right">
<tbody>
<tr><td align="right" valign="middle" width="50%">Services Charges</td>
<td align="right" valign="middle" width="50%">Rs. '+servicecharge+'</td>
</tr> ';
if(something >=0)
{
html += '<tr><td align="right" valign="middle">Sur Charges</td>
<td align="right" valign="middle">Rs. '+surcharge+'</td>
</tr>';
}
html += '<tr style="border:none;"><td align="right" valign="middle">VAT</td>
<td align="right" valign="middle"><strong>Rs. '+VAT+'</strong></td>
</tr><tr style="border:none;"><td align="right" valign="middle">Sub Total</td>
<td align="right" valign="middle"><strong>Rs. '+subtotal+'</strong></td>
</tr>
</tbody>
</table>
<br><br><br>
</section>';
divhtml.append(html);
答案 1 :(得分:0)
您需要拆分html以使用jQuery执行此操作或使用模板引擎。
使用jQuery,您可以:
divhtml.append('<div>Some content</div>');
if (foo > 0) {
divhtml.append('<div>Some conditional content</div>');
}
divhtml.append('<div>Some content</div>');
这是主要的想法,当然最好将html作为字符串存储在var中,并且只调用一次附加。
答案 2 :(得分:0)
仅使用js:
var html = "<div> first part before the condition"
if (something >= 0) {
html += "condition part";
}
html += "end part of the html";
// then using jquery to apeend html to the jquery object's DOM
$divhtml.append(html);
您还可以使用一些模板库,例如把手http://handlebarsjs.com/:
<div>
{{#if condition}}
<h1>shows only something >= 0</h1>
{{/if}}
</div>
html = Template.Sometemplate({condition:something >= 0});
$divhtml.append(html);