gpt4 book ai didi

javascript - 窗口和警报对象/函数在 Underscore 模板中不可用?

转载 作者:行者123 更新时间:2023-12-03 11:02:46 25 4
gpt4 key购买 nike

我正在尝试访问我的 Underscore 模板中名为“teams”的变量,事实证明这是我做过的最困难的事情之一。但我现在的问题是 - 为什么我不能在模板 javascript 代码中调用alert() 或 window.alert() ?

这是模板:

<script id="user-home-main-table-template" type="text/template">

<table class="table">
<thead>
<tr>

<th>Club</th>
<th>Sport</th>
<th>Delete?</th>

</tr>
</thead>
<tbody>


<%

if(teams == null){
alert('teams is null'); //alert is not defined
window.alert('teams is null'); //window is not defined either
var teams = {};
}

for(var i=0; i
<teams.length; i++) { %>
<tr>

<td>
<a class="font-big" href='/users/<%=user._id%>/teams/<%=teams[i]._id%>/teamDashboard'>
<%=teams[i].club %>
</a>
</td>
<td>
<a class="font-big" href='/users/<%=user._id%>/teams/<%=teams[i]._id%>/teamDashboard'>
<%=teams[i].sport %>
</a>
</td>
<td>
<a class="btn btn-warning" onclick=window.userHomeMainTableView.deleteTeam('<%=teams[i]._id%>');>delete</a>
</td>
</tr>
<% } %>
</tbody>
</table>
</script>

由于某种原因,alert() 和 window.alert() 在此模板脚本中不可用。这有充分的理由吗?

最佳答案

是的,这是有充分理由的。

您的模板将使用您传入的数据执行。

来自documentation :

When you evaluate a template function, pass in a data object that has properties corresponding to the template's free variables

var compiled = _.template("hello: <%= name %>");
compiled({name: 'moe'});
=> "hello: moe"

因此,当您将数据发送到模板时,它不包含 window 属性 - 也不应该包含!

如果您需要调试函数执行,只需在运行时进入模板执行即可。在 Chrome 中,在 Debug模式下,您可以通过按 F11 来“单步执行”。

关于javascript - 窗口和警报对象/函数在 Underscore 模板中不可用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28007398/

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