我有一些脚本可以将小部件滑出并在点击时隐藏它,它会在点击时显示但不会隐藏。
我在控制台中看到此错误
未捕获的TypeError:无法设置属性' onclick'为null
我不确定为什么我的小部件在点击id="closewiget"
(function (window) {
'use strict';
function classReg(className) {
return new RegExp("(^|\\s+)" + className + "(\\s+|$)");
}
var hasClass, addClass, removeClass;
if ('classList' in document.documentElement) {
hasClass = function (elem, c) {
return elem.classList.contains(c);
};
addClass = function (elem, c) {
elem.classList.add(c);
};
removeClass = function (elem, c) {
elem.classList.remove(c);
};
}
else {
hasClass = function (elem, c) {
return classReg(c).test(elem.className);
};
addClass = function (elem, c) {
if (!hasClass(elem, c)) {
elem.className = elem.className + ' ' + c;
}
};
removeClass = function (elem, c) {
elem.className = elem.className.replace(classReg(c), ' ');
};
}
function toggleClass(elem, c) {
var fn = hasClass(elem, c) ? removeClass : addClass;
fn(elem, c);
}
window.classie = {
hasClass: hasClass,
addClass: addClass,
removeClass: removeClass,
toggleClass: toggleClass,
has: hasClass,
add: addClass,
remove: removeClass,
toggle: toggleClass
};
})(window);
var
menuRight = document.getElementById('cbp-spmenu-s2'),
showRight = document.getElementById('showRight'),
closewiget = document.getElementById('closewiget'),
body = document.body;
showRight.onclick = function () {
classie.toggle(this, 'active');
classie.toggle(menuRight, 'cbp-spmenu-open');
$('.onetwothree').attr('src','');
$('.onetwothree').attr('src','https://embed.widgetpack.com/widget/img/google_rating_logo_36.png');
};
closewiget.onclick = function () {
classie.toggle(this, 'active');
classie.toggle(menuRight, 'cbp-spmenu-open');
$('.onetwothree').attr('src','');
$('.onetwothree').attr('src','https://embed.widgetpack.com/widget/img/google_rating_logo_36.png');
};
UPDATE请求添加HTML
我在其他JS文件中使用id="closewiget"
var averageRating = '<div class="da-all db-all" style="margin-bottom:110px">' +
'<h4>' +
'<img class="db-hide onetwothree" style="padding-top:5px;" src="https://embed.widgetpack.com/widget/img/google_rating_logo_36.png" alt=' + firmname + '>' +
'<span class="da2-da6 db1-db3" style="font-size: 1.1rem">' + firmname + '</span>' +
'<i class="da8 db4 fa fa-angle-double-right" id="closewiget" aria-hidden="true"></i>' +
'<div class="da2-da5 db1-db3" style="font-size: 1.3rem">' +
'<em class="da6-da8" id="em-padd" style="font-size: 1.3rem;">' + averageRatingResult + '</em>';
答案 0 :(得分:1)
这可能意味着元素还没有在DOM中。所以这个javascript位于页面源中的元素之上。
您可以使用onload
个活动,setTimeout
来电或重新排序HTML来解决此问题。
答案 1 :(得分:0)
如果您已经使用jQuery,为什么要使用document.getElementById然后尝试分配onclicks?
$('#cbp-spmenu-s2').click(function() {
classie.something();
// do stuff
});