我将信息发送到包含数组的客户端,并且我只显示数组的3个元素,因为我想具有分页效果。我想在js文件中编写分页代码
在file.js中
$(function(){
$(".pageLinks a").on("click", function(e){
e.preventDefault();
var pageNum = $(this).attr("id")
var test = JSON.stringify(populated) // I wanted populated to be the array from node
//doesn't have to have the stringify part
// I know I can't do this prob bec. it's not in an ejs file but I wanted something like that
console.log(test)
})
})
我可以在ejs文件中访问它
<% var index = Math.floor( populated.reviews.length /3)%>
<div class = "pageLinks">
<%for(var i = 0; i < index; i++){%>
<a href= "<%=i + 1%>" id = "<%=i%>"><%= i + 1 %> </a>
<%}%>
</div>
</div> <!--reviewSide-->
最佳答案
没错,您无法以相同的方式访问(静态)js文件中的原始对象。
但是,您可以将其填充到ejs文件中的全局变量,如下所示:
<script type="text/javascript">
var populated = <%-JSON.stringify(populated)%>;
</script>
然后您可以像这样在点击处理程序中进行检查:
$(function(){
$(".pageLinks a").on("click", function(e){
e.preventDefault();
var pageNum = $(this).attr("id")
if (typeof(populated) != "undefined"){
// you want to check to make sure this exists before trying to use
// it, just in case someone manages to click a page link before the
// code in your .ejs file has run.
var test = JSON.stringify(populated)
console.log(test)
}
})
})
...或在加载时传递给外部file.js,只要将某些内容公开给它可以调用的全局范围即可。您当前的脚本将所有内容包装在一个匿名函数中,但是您可以将其包装在一个命名函数中,如下所示:
.ejs文件:
<script type="text/javascript">
initialiseMyAwesomeFunction( <%-JSON.stringify(populated)%> );
</script>
.js文件:
function initialiseMyAwesomeFunction(populated){
$(function(){
$(".pageLinks a").on("click", function(e){
e.preventDefault();
var pageNum = $(this).attr("id")
var test = JSON.stringify(populated)
console.log(test)
})
})
}
关于javascript - 尝试访问js文件中的ejs数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40295075/