I have a LAMP server running in a VM, which is currently running fine. Now I would like to have a button on the /magento page that toggles a div container for me. I tried different approaches and I just can't get a result on the homepage.

I change the file "

/app/design/frontend/myvendor/Magento_Theme/layout/default_head_blocks.xml

,

default_head_blocks.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">
<body>
    <reference name="head">
        <action method="addJs"><script>js/extend.js</script></action>
    </reference>
</body>
</page>

extend.js

define([
    "jquery"
], function($){
    "use strict";
    return function() {
        alert("Hello");
    }
}

) It would be best if the .js file would only be used in the block (which was created via the Admin Portal)

I used this tutorial for example: https://devdocs.magento.com/guides/v2.3/javascript-dev-guide/javascript/js-resources.html

Tried Solution

My Hierachy

app/frontend/myvendor/Magento_Theme/
.../templates/custom.phtml
.../web/
    .../css/source/_extend.less
    .../js/myfile.js
.../requirejs-conf.js

And the content as specified by @PЯINCƏ

有帮助吗?

解决方案

To include your js file in theme :

Supposing that your js file is: myfile.js

app/design/frontend/{Vendor}/{theme}/requirejs-config.js

var config = {
    map: {
        '*': {
            myscript: 'js/myfile'
        }
    }
};

app/design/frontend/{Vendor}/{theme}/web/js/myfile.js

define(['jquery'], function($){
   "use strict";
       return function myscript()
       {
           alert("Yes, got it.");
       }
});

app/design/frontend/{Vendor}/{theme}/Magento_Theme/templates/{yourfile}.phtml

<script>
    require(['jquery', 'myscript'], function($, myscript) {
        myscript();
    });
</script>

 

clean the cache

clean var/view_preprocessed content

clean pub/static content

deploy the static content = php bin/magento setup:static-content:deploy -f
许可以下: CC-BY-SA归因
scroll top