正确包含Magento2自定义JQuery文件,但代码不';行不通
我在路径中添加了一个名为正确包含Magento2自定义JQuery文件,但代码不';行不通,jquery,magento2,Jquery,Magento2,我在路径中添加了一个名为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
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();
}
});
});
});
<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>
并修改了文件csproduct\u vproducts\u simple.xml
在小路上
app/code/Ced/CsProduct/view/frontend/layout/
文件的内容如下所示:
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();
}
});
});
});
<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调试器源代码中,该文件不存在
显然,我犯了一些愚蠢的错误,忽略了我的注意力。这似乎不是正确的方法。(我的看法) 您需要在此路径
/app/design/frontend/VendorName/Theme/web/js/
中使用以下内容requirejs config.js
:
var config = {
map: {
'*': {
custom_js: 'VendorName_ModuleName/js/js_file_name'
}
}
};
在模板中,您可以将其称为:
<script>
require([
'jquery',
'custom_js'
], function ($, script) {
//Your code here
//alert('Here');
});
要求([
“jquery”,
“自定义_js”
],函数($,脚本){
//你的代码在这里
//警报(“此处”);
});
您也可以通过以下线程中的St3phan
检查一个很好的解释:
希望有帮助