【问题标题】:Liquid/Shopify: how I add jQuery to the page?Liquid/Shopify:如何将 jQuery 添加到页面中?
【发布时间】:2017-10-10 04:15:16
【问题描述】:

我很难将外部 jQuery 库集成到我自己的流动页面中。我想用 CDN 加载它。

theme.liquid 页面上,我以这种方式加载 Javascript:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
{{ 'spot-the-ball.js' | asset_url | script_tag }}

spot-the-ball.js 内部,我有一个纯Javascript .onload 函数,它是workig。然后我有以下不工作的 jQuery:

$( '.coords' ).mousemove(function ( e ) {
                // console.log(e.clientX);
                // var x = ( ( e.clientX - left ) / width ).toFixed( 1 ),
                //     y = ( ( height - ( e.clientY - top ) ) / height ).toFixed( 1 );

                    x = e.clientX - 50;
                    y = e.clientY - 50;

                $( tooltip ).text( x + ', ' + y ).css({
                    left: e.clientX - 30,
                    top: e.clientY - 30
                }).show();
            });

$( '.coords' ).mouseleave(function () {
                $( tooltip ).hide();
            });

    $(".coords").mouseup(function(){
      $('.yourcoordinates').append("X:",x," Y:",y)
    });    $( '.coords' ).mousemove(function ( e ) {
                // console.log(e.clientX);
                // var x = ( ( e.clientX - left ) / width ).toFixed( 1 ),
                //     y = ( ( height - ( e.clientY - top ) ) / height ).toFixed( 1 );

                    x = e.clientX - 50;
                    y = e.clientY - 50;

                $( tooltip ).text( x + ', ' + y ).css({
                    left: e.clientX - 30,
                    top: e.clientY - 30
                }).show();
            });

$( '.coords' ).mouseleave(function () {
                $( tooltip ).hide();
            });

    $(".coords").mouseup(function(){
      $('.yourcoordinates').append("X:",x," Y:",y)
    });

【问题讨论】:

  • 检查开发控制台是否有任何错误,然后写一个简单的console.log('test')并检查JS是否加载,第三检查目标元素是否实际加载,然后再定位它们console.log($( '.coords' ).length) . 99% 的时间你会以这种方式发现问题。
  • 是的,有错误,我将回答我自己的问题,以便每个人都能看到解决方案。谢谢

标签: javascript jquery shopify liquid


【解决方案1】:

我在项目中有另一个使用旧版本 jQuery 的 js 文件。控制台显示错误。 我加载了一个较旧的 CDN,现在一切正常。

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.js" type="text/javascript"></script>

【讨论】:

    【解决方案2】:

    你可以把它放在你的模板中,例如theme.liquid

    {{ '//ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js' | script_tag }}
    

    【讨论】:

    • 是的,我确实是这样做的。即使没有液体sintax,它也可以工作,只是简单的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-14
    • 1970-01-01
    • 2022-11-11
    相关资源
    最近更新 更多