本文介绍了在 Jade 中,如何调用外部 Javascript 中的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在/javascripts/showlist.js 我有(还有一些没有显示)

In /javascripts/showlist.js I have (plus some more not shown)

var interestMap = gets loaded from localStorage...

function getInterest(id) {
   return interestMap[id] || '';
}

我的 showlist.jade 文件看起来像:(大大简化,它在变量shows"中的一组 dogshows 中传递)

My showlist.jade file looks like: (greatly simplified, it gets passed in an array of dogshows in the variable "shows")

extends layout

script(src='/javascripts/showlist.js')

block content

  table#showtable.sortable
    thead
      tr
         td... (column headers such as date and location, many are sortable)
    tbody
      each show in shows
         - var interest = getInterest(show._id);  <<< JADE problem here
         tr
           td... (various values, including)
           td =interest   // maybe this should be #{interest}

但是当我尝试调用 getInterest() 时,我得到未定义不是函数".所以它没有看到它.我还尝试了对外部 javascript 的轻微修改

but I get "undefined is not a function" when I try to call getInterest(). So it's not seeing it. I've also tried a slight mod to the external javascript

var getInterest = function(id) { ... }

并将 getInterest 代码内联,但都没有成功.

and putting the getInterest code inline, neither with any success.

请注意,此扩展的基本布局将 doctype 5 作为第一行.

Note that the base layout this is extending has doctype 5 as it's first line.

您如何从 Jade 调用外部(或者,我什至会满足于内部)javascript 函数.还是我错过了一些简单而愚蠢的东西?我也尝试过../javascripts/showlist.js".

How do you call an external (or, I'll even settle for an internal) javascript function from Jade. Or am I missing something simple and silly? I did try "../javascripts/showlist.js" too.

推荐答案

您正在尝试在服务器端调用客户端函数.这就是为什么它返回未定义的原因.这里不存在.

You're trying to call a client side function on the server side. Which is why it is coming back as undefined. It doesn't exist here.

您的 jade script() 标签只是将 <script> 标签输出到页面 - 它不是在服务器端运行.为此,您将使用 require() 代替.

Your jade script() tag is simply outputting a <script> tag to the page - it is not running it server side. To do that, you'd be using require() instead.

既然你指的是localStorage,你不能简单地复制服务器端的函数并在那里执行它.

Since you are referring to localStorage, you cant simply copy the function on the server side and execute it there too.

但是,您可以更新您的 showlist.js,以便在 dom 就绪时,它会使用它们的兴趣值更新 td .使用 show id 将 html5 数据属性添加到您的 td.例如.

You can, however, update your showlist.js so that on dom ready it updates the tds with their interest value. Add a html5 data attribute to your td with the show id. eg.

td(data-show-id=show._id)

然后找到需要更新的td并调用getInterest():

Then find tds that need updating and call getInterest():

$('td[data-show-id]').each(function(index){
    var $el = $(this);
    $el.val(getInterest($el.data('show-id')));
});

假设您正在运行 jQuery.

Presuming you are running jQuery.

这篇关于在 Jade 中,如何调用外部 Javascript 中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 01:55