试图访问js文件中的ejs数组

时间:2016-10-27 22:16:19

标签: javascript arrays node.js express ejs

我将信息发送到包含数组的客户端,我只显示数组的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-->

1 个答案:

答案 0 :(得分:2)

你是对的,你不能以同样的方式到达(静态)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)
         })
     })
}