简体   繁体   English

在Jade中,如何在外部Javascript中调用函数

[英]In Jade, how can you call a function in an external Javascript

In /javascripts/showlist.js I have (plus some more not shown) 在/javascripts/showlist.js中,我(还有一些未显示)

var interestMap = gets loaded from localStorage...

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

My showlist.jade file looks like: (greatly simplified, it gets passed in an array of dogshows in the variable "shows") 我的showlist.jade文件看起来像:(大大简化了,它在变量“ shows”中的dogshow数组中传递)

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}

but I get "undefined is not a function" when I try to call getInterest(). 但是当我尝试调用getInterest()时,我得到“未定义的不是函数”。 So it's not seeing it. 因此,它没有看到它。 I've also tried a slight mod to the external javascript 我还尝试了对外部javascript的轻微修改

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

and putting the getInterest code inline, neither with any success. 并将getInterest代码内联,但均未成功。

Note that the base layout this is extending has doctype 5 as it's first line. 请注意,此扩展的基本布局的第一行具有doctype 5

How do you call an external (or, I'll even settle for an internal) javascript function from Jade. 您如何从Jade调用外部(或什至是内部的)JavaScript函数。 Or am I missing something simple and silly? 还是我错过了一些简单而愚蠢的事情? I did try "../javascripts/showlist.js" too. 我也尝试过“ ../javascripts/showlist.js”。

You're trying to call a client side function on the server side. 您正在尝试在服务器端调用客户端函数。 Which is why it is coming back as undefined. 这就是为什么它返回为undefined的原因。 It doesn't exist here. 它在这里不存在。

Your jade script() tag is simply outputting a <script> tag to the page - it is not running it server side. 您的jade script()标记只是在页面上输出<script>标记-它不在服务器端运行。 To do that, you'd be using require() instead. 为此,您将改为使用require()

Since you are referring to localStorage, you cant simply copy the function on the server side and execute it there too. 由于您指的是localStorage,因此不能简单地在服务器端复制功能并在其中执行它。

You can, however, update your showlist.js so that on dom ready it updates the td s with their interest value. 但是,您可以更新showlist.js以便在dom准备就绪时以其兴趣值更新td Add a html5 data attribute to your td with the show id. 使用显示ID将html5数据属性添加到您的td。 eg. 例如。

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

Then find td s that need updating and call getInterest(): 然后找到需要更新的td ,并调用getInterest():

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

Presuming you are running jQuery. 假设您正在运行jQuery。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM