【问题标题】:Magento2 Custom JQuery file included correctly but code doesn't workMagento2 自定义 JQuery 文件包含正确,但代码不起作用
【发布时间】:2018-06-16 19:57:22
【问题描述】:

我在路径中添加了一个名为myweb.js的自定义js文件 /app/code/Ced/CsProduct/view/frontend/web/js/

代码是这样的:

require([
    "jquery"
    ], function($){
    $(document).ready(function() {
    alert("Hello");
    $("[data-index='painting_hieght']").hide();
    $("[name='product[size]']").change(function(){
     var status = this.value;
     alert(status);
   if(status=="103"){
      $("[data-index='painting_hieght'],[data-index='painting_width']").show();// hide multiple sections
        }else {
            $("[data-index='painting_hieght'],[data-index='painting_width']").hide();
        }
  });
    });
   });

并修改了文件csproduct_vproducts_simple.xml 在路径中 app/code/Ced/CsProduct/view/frontend/layout/

文件的内容如下所示:

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">

        <head>
        <link src="Ced_CsProduct::js/myweb.js"/>
        </head>
    <update handle="csproduct_vproducts_superconfig_config"/>
</page>

我收到了正确的警报hello,这意味着该文件被正确包含。 但是之后的代码似乎不起作用,尽管我已经测试了在 firebug 控制台中工作的代码。

我在这里缺少什么?

更新:

进一步观察,我发现我在清除所有缓存后第一次收到警报“Hello”。 但随后的重新加载不会显示任何警报。 除了页面源显示myweb.js 但在 firebug 调试器源中,该文件不存在。

显然我犯了一些愚蠢的错误,这让我没有注意。

【问题讨论】:

    标签: jquery magento2


    【解决方案1】:

    这似乎不是正确的做法。 (我的看法)

    你需要requirejs-config.js在这条路径/app/design/frontend/VendorName/Theme/web/js/下面的内容:

    var config = {
        map: {
            '*': {
                custom_js: 'VendorName_ModuleName/js/js_file_name'
            }
        }
    };
    

    在模板中你可以调用它:

    <script>
        require([
            'jquery',
            'custom_js'
        ], function ($, script) {
            //Your code here
            //alert('Here');
        }); 
    

    您也可以在下面的线程中查看St3phan 的精彩解释: https://magento.stackexchange.com/questions/190821/magento2-add-js-from-admin-cms-page-design-layout-update-xml

    希望有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-03-27
      • 1970-01-01
      • 2017-01-03
      • 2017-07-08
      • 2018-03-26
      • 2010-12-21
      • 1970-01-01
      相关资源
      最近更新 更多