如何在JavaScript函数中的html中插入条件语句?

时间:2017-09-22 03:28:22

标签: javascript jquery html

这是我的代码:

System.NullReferenceException: Object reference not set to an instance 
of an object
at MonoTouch.Design.Client.IPhoneDesignerSession  +
 <MaybeConvertToLatestXcode>c__async5.MoveNext () [0x0004c] in 
 /Users/builder/data/lanes/4470/6c2f6737/source/md-
 addins/Xamarin.Designer.iOS/MonoTouch.Design.Client/
 IPhoneDesignerSession.cs:774 
 --- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () 
[0x0000c] in /private/tmp/source-mono-d15-3/bockbuild-d15-
3/profiles/mono-mac-xamarin/build-root/mono-
x64/mcs/class/referencesource/mscorlib/system/runtime/
exceptionservices/exceptionservicescommon.cs:151 
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess 
(System.Threading.Tasks.Task task) [0x00037] in /private/tmp/source-
mono-d15-3/bockbuild-d15-3/profiles/mono-mac-xamarin/build-root/mono-
x64/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/
TaskAwaiter.cs:187 

我想在其中插入条件语句,如

var tr = `<tr>
    <td>${flippableTemplate(item['Group 1'])}</td>
    <td>${flippableTemplate(item['Group 2'])}</td>
    <td>${item['Description']}</td>             
    <td>${item['Description2']}</td>
</tr>`;

我该怎么做?

任何形式的帮助将不胜感激。感谢。

2 个答案:

答案 0 :(得分:1)

您可以使用解决方案https://jsfiddle.net/vh1bmfuz/

&#13;
&#13;
var item = { Category: 1, Description: 'Description 1.1', 'Description 2': 'Description 1.2', status: 'Status 1', 'Group 1': 'group1.1', 'Group 2': 'group1.2', 'A': 1, 'B': 2}

var matchMethod = function(){
  return ((item['A'] != item['B']) ? 'Great' : 'Ops');
}


var tr = `<tr>
    <td>${item['Group 1']}</td>
    <td>${item['Group 2']}</td>
    <td>${item['Description']}</td>             
    <td>${item['Description 2']}</td>
    <td>${matchMethod()}</td>
</tr>`;

$('table').append(tr);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table></table>
&#13;
&#13;
&#13;

我有一种方法可以检查&amp;根据匹配的条件返回一个字符串。

希望这会对你有所帮助。

答案 1 :(得分:0)

为什么不创建一个接收输入,测试它们然后输出模板的函数?

function appendCell(a, b) {
  const word = a !== b ? 'Great' : 'Oops';
  return `<tr><td>1</td><td>2</td><td>3</td><td>4</td><td>${word}</td></tr>`;
}

const a = 1;
const b = 2;
const output = appendCell(a, b);

输出

<tr><td>1</td><td>2</td><td>3</td><td>4</td><td>Great</td></tr>

根据您的要求调整代码。

<强> DEMO