JQuery - 将字符串转换为对象并添加 "click" 事件在模块模式中不起作用
JQuery - converting string to an object and adding "click" event not working in a module pattern
我想为我的 JS 创建模块模式,我想将所有 DOM 引用存储在对象中,但它必须是字符串,因为 DOM 稍后创建。稍后我想使用函数将 "click" 事件添加到所有存储的选择器,问题是无论我尝试什么,我都无法以某种方式将它们转换为正确的 jQuery 对象。经典的 $(...) 似乎不起作用,我不知道发生了什么。我现在得到 "TypeError: a is not an object",之前的尝试我有 "b is undefined" 等等。
如何解决这个问题??
var Obj = {
dom: {
element1: ".image",
element2:".image2"
},
init: function () {
$.each(Obj.dom, Obj.setup);
},
setup: function () {
console.log(this); // String ".image" -GOOD
var item = $(this);
console.log(item); // Object ".", "i", "m" ... - kinda weird,
// why is this divided by 1 character ??
$(item).on("click", function () { // TypeError: a is not an object
console.log('works');
});
}
};
Obj.init();
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
this
的值不完全是字符串。它是一个对象,您需要将其转换为字符串。
console.log(typeof this) // object
console.log(this + ''); // String ".image"
var item = $(this + ''); // works
console.log(item); // now you have jquery object
我想为我的 JS 创建模块模式,我想将所有 DOM 引用存储在对象中,但它必须是字符串,因为 DOM 稍后创建。稍后我想使用函数将 "click" 事件添加到所有存储的选择器,问题是无论我尝试什么,我都无法以某种方式将它们转换为正确的 jQuery 对象。经典的 $(...) 似乎不起作用,我不知道发生了什么。我现在得到 "TypeError: a is not an object",之前的尝试我有 "b is undefined" 等等。
如何解决这个问题??
var Obj = {
dom: {
element1: ".image",
element2:".image2"
},
init: function () {
$.each(Obj.dom, Obj.setup);
},
setup: function () {
console.log(this); // String ".image" -GOOD
var item = $(this);
console.log(item); // Object ".", "i", "m" ... - kinda weird,
// why is this divided by 1 character ??
$(item).on("click", function () { // TypeError: a is not an object
console.log('works');
});
}
};
Obj.init();
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
this
的值不完全是字符串。它是一个对象,您需要将其转换为字符串。
console.log(typeof this) // object
console.log(this + ''); // String ".image"
var item = $(this + ''); // works
console.log(item); // now you have jquery object