gpt4 book ai didi

javascript - 在 {{/if}} 中打开一个 div 并稍后使用 Meteor/blaze 关闭它

转载 作者:行者123 更新时间:2023-12-03 00:20:12 27 4
gpt4 key购买 nike

我正在尝试制作一些仅在 HTML/Blaze 中无法实现的东西。

我的意思是我试图在 {{#if}} 中打开一个 div,而不在这个特定的 if 中关闭它。不可能通过以下方式做到这一点:

{{#each getData}}
{{#if equals this.level first}}
<div><p>content</p>
{{/if}}
{{#if equals this.level last}}
</div>
{{/if}}}
{{/each}}

所以我找到了可以解决这个问题的东西。使用三重花括号并在 JS 中生成 HTML 部分。

{{#each getData}}
{{{getContent this}}}
{{/each}}

getContent() 返回我的 HTML。它看起来像这样:

getContent(obj) {
if (obj.level == first)
return "<div><p>content</p>";
if (obj.level == last)
return "<p>content></div>";
else
return "<p>content</p>";
}

它可以工作,它可以渲染 HTML,但有一个问题。我打开的 div 似乎会自行关闭。

这就是渲染的内容:

<div><p>Content</p></div>
<p>content</p>
<p>content</p>

而不是:

<div><p>content</p>
<p>content</p>
<p>content</p>
</div

我真的很累,如果我不够清楚或者解决方案很明显,我很抱歉。

编辑:我现在拥有的并且工作正常,如下:

HTML

{{#with getDataFromButton}}
{{formatData this}}
{{/with}}

JS

formatData(data) {
var res = "";
for (var i = 0; i < data.length; i++) {
if (data[i]["level"] == 0) {
if (res.length > 0)
res += "</div>";
res += "<div class=\"whiteBox\"><p>" + data[i]["value"] + "</p>";
}
else if ('last' in data[i]) {
res += "<p>" + data[i]["value"] + "</p></div>";
}
else {
res += "<p>" + data[i]["value"] + "</p>";
}
}
return res;
},

谢谢大家的解释!新年快乐(现在还不算太晚)。

最佳答案

这样做是因为浏览器会尝试修复任何更改的 HTML 结构。如果您使用 Blaze,则 HTML 会在客户端呈现,并且在辅助代码的任何评估中都会注入(inject)到 DOM。然后浏览器获取此 HTML 并尝试修复它。

最好的解决方案是使用简单模式

<div>
{{#each getData}}
<p>content</p>
{{/each}}
</div>

如果您想应用您所提供的逻辑,您必须在 JS 中准备完整正确的 HTML 元素。您可以按如下方式操作。

在模板类型中:{{ myFullCorrectNodeElement }}

在 JS 中输入:

helpers: {
myFullCorrectNodeElement() {
let html = "";
const data = Template.instance().getData;
for(let i=0; i<data.length; i++) {
// your logic
if(i===0) {
html += `<div><p>content</p>`
// there you can access to variables by syntax ${}
// insde of ``, you can read about template strings from ES6
}
// ... and rest of your logic
}
return html;
}
}

关于javascript - 在 {{/if}} 中打开一个 div 并稍后使用 Meteor/blaze 关闭它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54351320/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com