javascript - Symfony2 Jquery 没有做任何事情

标签 javascript jquery symfony twig

所以我用 jQuery 做了一个简单的函数来检查它是否有效。我不知道为什么会发生这种情况,因为我做了在其他堆栈问题上发现的所有内容。它只是没有做任何事情...

到目前为止我所做的一切:

1)我创建了脚本并将其保存在文件中:

$('.plus').on('click', function (e) {
    $this = $(this);
    alert("product id "+$this.parent('.item').find('input').data('id') + " Quantity "+$this.parent('.item').find('input').val())
});

2)我在 twig 中添加了代码以使脚本正常工作:

<div class="item">
    <input type="text" value="2" data-id="1" />
    <a href="javascript:void(0)" class="plus">+</a>
    <a href="javascript:void(0)">-</a>
</div>
<div class="item">
    <input type="text" value="2" data-id="2" />
    <a href="javascript:void(0)" class="plus">+</a>
    <a href="javascript:void(0)">-</a>
</div>
<div class="item">
    <input type="text" value="2" data-id="3" />
    <a href="javascript:void(0)" class="plus">+</a>
    <a href="javascript:void(0)">-</a>
</div>

现在,在我的 base.html.twig 中,我将 jquery 库添加到了我的 assetics 中:

{% 阻止 JavaScript %}

        {# Le Javascript #}         
            {% javascripts 

                'bundles/mpFrontend/assets/js/jquery-1.11.2.min.js' // the jquery library       

                %}    

                <script src="{{ asset_url }}"></script>       
            {% endjavascripts %}

    {% endblock %}

然后在我的索引 html 中,我想让脚本工作:

1) 扩展基本 Twig :{% extends "::base.html.twig"%}

2)我访问脚本:

{% block javascripts %} 
    {{ parent() }}  
    {% javascripts 'js/scripts.js'%}
         <script type="text/javascript" src="{{ asset_url }}"></script>
    {% endjavascripts %}
{% endblock %}

4)我执行 assetic:dump :

php app/console assetic:dump

5) 我在 config.yml 中添加了 bundle ,因为我收到错误:您必须将“”添加到 assetic.bundle 配置:

assetic:
    debug:          "%kernel.debug%"
    use_controller: false
    bundles:        [ MpShopBundle ]

这就是我所做的,但代码仍然无法工作。 dump 命令没有给我任何错误,这意味着路由是正确的。但是该脚本不起作用...

最佳答案

您需要将 javascript 代码包装在 jQuery 的 ready 事件中。

$(document).ready(function () {
    $('.plus').on('click', function (e) {
        $this = $(this);
        alert("product id " + $this.parent('.item').find('input').data('id') + " Quantity " + $this.parent('.item').find('input').val())
    });
});

关于javascript - Symfony2 Jquery 没有做任何事情,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30071672/

相关文章:

jquery - 淡出而不折叠

symfony - 将 Memcached 服务添加到 symfony2

php - Symfony 控制台 - 创建文件?

symfony - 如何将 token 存储作为参数传递给 Symfony 3.4 中的事件监听器

javascript - 获取 JavaScript 编译器生成的汇编代码

javascript - 如果没有可用的缓存,则使用 Ajax 请求

javascript - 如何使用 javascript 在 href 上禁用 google chrome 中的新选项卡选项

javascript - 在 Feathers JS 中从 rethinkdb 中查找嵌套数组对象

javascript - 从字符串中删除引号/字符串的替代方案

javascript - 左右箭头移出图像时不会淡出