如果不在对象数组内部触发
if not trigger inside object array
对象数组在使用 forEach 调用方法时不执行“if”,但是当我将 if 移到 forEach 内部时它起作用了,我试图弄清楚为什么不触发对象内部的 if 运行 forEach.
有一个带有默认值 (false) 的 var (responseFlag),所以如果您需要更改 html 渲染,只需在单击按钮时更改它 (true/false)。
var responseFlag = false,
targetRender = document.getElementById('targethtml'),
templateTrue = '<h2>true</h2>',
templateFalse = '<h2>false</h2>';
//
objDef = {
"objDefs" : [
{
"UIhtml": responseFlag == true ? templateTrue : templateFalse // does not works
// "UIhtml": responseFlag // this works
}
]
};
//
UI_exc = {
outputResult: function() {
objDef.objDefs.forEach(function(key, value){
targetRender.innerHTML =
// responseFlag == true ? templateTrue : templateFalse // this works
key.UIhtml // does not works
console.log(responseFlag)
});
},
clickAction: function() {
document.getElementById('goRender').addEventListener("click", function(){
responseFlag = true //
console.log(responseFlag);
UI_exc.outputResult()
});
}
};
UI_exc.clickAction();
<button id="goRender">Click</button>
<div id="targethtml">[ N ]</div>
创建对象文字时,声明的属性不是字符串,而只是对某些值的引用,例如字符串、数字、布尔值、对象...
将“UIhtml”更改为 UIhtml。
阅读此文档以获取更多信息:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object
我猜的问题是对象被初始化并且 UIhtml 属性 被分配在那里,我认为你应该将 UIhtml
更改为一个函数然后调用它:
... = key.UIhtml()
console.log(responseFlag)
对象数组在使用 forEach 调用方法时不执行“if”,但是当我将 if 移到 forEach 内部时它起作用了,我试图弄清楚为什么不触发对象内部的 if 运行 forEach.
有一个带有默认值 (false) 的 var (responseFlag),所以如果您需要更改 html 渲染,只需在单击按钮时更改它 (true/false)。
var responseFlag = false,
targetRender = document.getElementById('targethtml'),
templateTrue = '<h2>true</h2>',
templateFalse = '<h2>false</h2>';
//
objDef = {
"objDefs" : [
{
"UIhtml": responseFlag == true ? templateTrue : templateFalse // does not works
// "UIhtml": responseFlag // this works
}
]
};
//
UI_exc = {
outputResult: function() {
objDef.objDefs.forEach(function(key, value){
targetRender.innerHTML =
// responseFlag == true ? templateTrue : templateFalse // this works
key.UIhtml // does not works
console.log(responseFlag)
});
},
clickAction: function() {
document.getElementById('goRender').addEventListener("click", function(){
responseFlag = true //
console.log(responseFlag);
UI_exc.outputResult()
});
}
};
UI_exc.clickAction();
<button id="goRender">Click</button>
<div id="targethtml">[ N ]</div>
创建对象文字时,声明的属性不是字符串,而只是对某些值的引用,例如字符串、数字、布尔值、对象...
将“UIhtml”更改为 UIhtml。
阅读此文档以获取更多信息: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object
我猜的问题是对象被初始化并且 UIhtml 属性 被分配在那里,我认为你应该将 UIhtml
更改为一个函数然后调用它:
... = key.UIhtml()
console.log(responseFlag)