简体   繁体   English

为什么我的onclick函数不适用于Mustache模板中的按钮?

[英]Why is my onclick function not working for the button inside a Mustache template?

I am trying to apply a event on a button but it doesn't seem to be responding to this code. 我试图在按钮上应用事件但它似乎没有响应此代码。 I am using mustache templates for my data but I am not sure if thats the problem for it to not to resposd to getElementById tag or something. 我正在为我的数据使用小胡子模板,但我不确定这是不是因为它没有重新发布到getElementById标签或其他东西。 Any help would be appreciated. 任何帮助,将不胜感激。

<script id="itemtpl" type="text/template">
    {{#items}}
            <div class ="item"> 
                <div class="item_image">
                    <img src = "{{item.image_url}}" />
                </div>
                <h3 class="item_name">{{item.menu_item_name}}</h3>
                <h4 class="item_price">${{item.menu_item_price}}</h4>
                <p class="item_description">    {{item.menu_item_description}}</p>
                <button type="button" class="addtocart" id="addtocart" >Add to Cart</button>
            </div>
    {{/items}}
    </script>

    <script>
        var addToCart = document.getElementById("addtocart");

        addToCart.onclick = function() {

        alert("Yayyy");

        }
    </script>

Set the onclick property after the mustache template is rendered. 渲染髭模板后,设置onclick属性。 getElementById will not find the element if it isn't yet in the DOM. 如果元素尚未在DOM中,则getElementById将找不到该元素。 Since the code that sets onclick is just in script tags without any sort of document.ready , it can execute before the page has finished rendering (and you have rendered the template). 由于设置onclick的代码仅位于脚本标记中,而没有任何document.ready ,因此它可以在页面完成渲染(并且您已经渲染模板)之前执行。 You don't want to set onclick until after you have rendered your mustache template. 在渲染胡子模板之前,您不希望设置onclick。 I suggest putting this code in a method and calling it after your render code. 我建议将此代码放在一个方法中,并在渲染代码后调用它。

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

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