【发布时间】:2018-06-16 12:30:33
【问题描述】:
我所做的是在现有的 js 文件中添加自定义 jquery 代码。
例如文件的内容是这样的:
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
define([
'uiComponent',
'jquery',
'ko',
'underscore',
'mage/translate',
],
function (Component, $, ko, _) {
'use strict';
return Component.extend({
......
现在在结束标记之前我添加了类似的行
....
updateNotifications: function(url){
var self = this;
$.getJSON(url,function(data){
self.customData.percent(data.statistics.percent);
self.customData.href(data.statistics.href);
self.customData.contentLoading(0);
self.customData.notifications(data.notifications);
self.customData.vendor(data.vendor);
setTimeout(function(){ self.updateNotifications(url); }, 60000);
});
}
});
$("[data-index='painting_hieght']").hide(); //this the line added by me
});
我希望在加载时隐藏字段/标签,但事实并非如此。 我已经在 firebug 控制台中测试了代码,效果很好。
如何将自定义 jQuery 代码集成到 Magetno Js 文件中。
更新:
我创建了一个名为 myweb.js 的自定义 Js 文件
并将其放在文件夹 custom Module js 文件夹中。
并将其包含在相关的布局 xml 文件中。
我使用的代码是这样的:
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();
}
});
});
});
我收到了正确的警报,
但其余代码没有任何效果。 但是如果我在 firebug 控制台中测试相同的代码,它可以正常工作。
【问题讨论】:
-
你在head里包含这个js文件吗?尝试在结束正文标记之前包含它
-
是的。文件本身被命名为
header.js -
我刚刚观察到该文件是通过
requirejs-config.js包含的,而不是在任何 xml 文件的头部。这可能是代码不起作用的原因吗? -
当 js 动态包含在 require 中时,可能是您的 DOM 尚未绘制,这就是您的代码无法正常工作的原因。尝试在 js 中的该行上保留一个断点,看看是否在 $("[data-index='painting_hieght']") 中获取任何元素。
-
@NanditaAroraSharma - 我已经更新了这个问题,如果你可以看看。至于警报,我只是在清理缓存后第一次得到它,但随后重新加载,甚至警报都丢失了。