2012-04-23 60 views
1

这一定比我想象的要简单。不知道发生了什么事。在手柄模板中访问DOM元素

我有一个DIV,我用手柄模板“填充”。生成模板后,我使用jQuery slideDown打开面板查看内容。现在我需要放一个关闭功能来滑动DIV。

我认为问题在于click函数没有被绑定,因为a.close元素在脚本标签内。

下面是对内容的DIV:

<div id="characteristic" style="bottom:0px; width:800px; display:none; position:fixed; left: 350px;"></div> 

这里是jQuery的片段。这是在HTML的顶部:

$(document).ready(function(e){ 
    $("a.close").click(function(e) { 
    e.preventDefault(); 
    $("#characteristic").slideUp(); 
    }); 
}); 

和模板片段:

<script id="ac-template" type="text/x-handlebars-template"> 
    <div class="holder" style="background-color:#FFFFFF;"> 
     <div class="frame"> 
      <div class="content"> 
       <div class="info-box-holder"> 
        <a class="close" href="">&times;</a> 
        <div class="heading"> 
         <h2>ACTIONABLE CHARACTERISTIC</h2> 
        </div> 
        <div class="info-box"> 
         <a href="#"><img class="alignleft" src="{{image_large}}" alt="" width="400" height="400" /></a> 
         {{#if subcategory_name}} 
          <h2>{{subcategory_name}}: {{name}}</h2> 
         {{else}} 
          <h2>{{category_name}}: {{name}}</h2> 
         {{/if}} 
+0

特征ID在哪里? – Amberlamps 2012-04-23 12:44:35

+0

也许您需要在模板渲染后运行准备好的函数中的代码,因为在onload期间控件可能不存在 – 2012-04-23 13:13:44

+0

@Amberlamps我已经添加了DIV的代码。 – spdaly 2012-04-23 14:17:56

回答

3

我知道这是一个老问题,你可能已经制定出了答案,但肯定,这是因为当时你的JS代码运行时,DOM中不存在a.close

您需要在handlebars完成呈现模板之后运行JS代码,或者绑定到页面加载时存在的更高级DOM元素(某种类型的容器),然后仅激活您想要的链接。像这样(see the API):

$(document).ready(function(e){ 
    $("#mycontainerdiv").on('click', 'div.info-box-holder a.close', function(e) { 
    e.preventDefault(); 
    $("#characteristic").slideUp(); 
    }); 
});