JS代码在JSFiddle中完美运行,但在Meteor中不起作用

时间:2015-10-07 13:38:25

标签: javascript jquery twitter-bootstrap meteor

我制作的脚本根据当天更改了活动的Bootstrap选项卡。正如您应该看到的,它在this JSFiddle上运行良好。

但是,我尝试过以几种方式将其添加到我的流星应用程序中,包括一次没有“流星化”它。这不起作用,所以我尝试查找并最终将选项卡式导航包装在<template name="nav">中。然后我尝试在Template.nav.onRendered块中加载脚本。这也不起作用,现在我很难过。

编辑:如果其他人遇到同样的问题,我遇到的问题是我在加载选项卡面板之前加载了脚本,因此会设置活动选项卡,但面板会不显示。

感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

根据你的小提琴,代码在渲染模板之前运行得太早。因此,您需要将代码包装在函数中,然后在Template.nav.onRendered内部运行它,如下所示:

function initializeTabs() {
...
}

然后

Template.nav.onRendered(initializeTabs);

答案 1 :(得分:0)

使用onRendered可以正常工作。

meteor create 32993732
cd 32993732
meteor add bootstrap

32993732.css:

body {
    padding: 1rem;
}

.tab-pane {
    padding: 1rem;
}

32993732.html:

<head>
</head>

<body>
  {{> hello}}
</body>
<template name="hello">
<div>

  <!-- Nav tabs -->
  <ul class="nav nav-tabs" role="tablist">
    <li role="presentation"><a href="#sunday" aria-controls="sunday" role="tab" data-toggle="tab">Sunday</a></li>
    <li role="presentation"><a href="#monday" aria-controls="monday" role="tab" data-toggle="tab">Monday</a></li>
    <li role="presentation"><a href="#tuesday" aria-controls="tuesday" role="tab" data-toggle="tab">Tuesday</a></li>
    <li role="presentation"><a href="#wednesday" aria-controls="wednesday" role="tab" data-toggle="tab">Wednesday</a></li>
    <li role="presentation"><a href="#thursday" aria-controls="thursday" role="tab" data-toggle="tab">Thursday</a></li>
    <li role="presentation"><a href="#friday" aria-controls="friday" role="tab" data-toggle="tab">Friday</a></li>
    <li role="presentation"><a href="#saturday" aria-controls="saturday" role="tab" data-toggle="tab">Saturday</a></li>
  </ul>

  <!-- Tab panes -->
  <div class="tab-content">
    <div role="tabpanel" class="tab-pane fade" id="sunday">Sunday</div>
    <div role="tabpanel" class="tab-pane fade" id="monday">Monday</div>
    <div role="tabpanel" class="tab-pane fade" id="tuesday">Tuesday</div>
    <div role="tabpanel" class="tab-pane fade" id="wednesday">Wednesday</div>
    <div role="tabpanel" class="tab-pane fade" id="thursday">Thursday</div>
    <div role="tabpanel" class="tab-pane fade" id="friday">Friday</div>
    <div role="tabpanel" class="tab-pane fade" id="saturday">Saturday</div>
  </div>

</div>
</template>

32993732.js:

if (Meteor.isClient) {
  Template.hello.onRendered( function(){
    var day;

    switch (new Date().getDay()) {
        case 0:
        day = "sunday";
        break;
        case 1:
        day = "monday";
        break;
        case 2:
        day = "tuesday";
        break;
        case 3:
        day = "wednesday";
        break;
        case 4:
        day = "thursday";
        break;
        case 5:
        day = "friday";
        break;
        case 6:
        day = "saturday";
        break;
    }

    $('.nav-tabs li a[href="#' + day + '"]').tab('show');

  });
}