简体   繁体   English

jQuery-将字符串转换为对象并添加在模块模式中不起作用的“ click”事件

[英]JQuery - converting string to an object and adding “click” event not working in a module pattern

I would like to create module pattern for my JS, and I would like to store all DOM references in object, but it has to be string since, DOM is creating later. 我想为我的JS创建模块模式,我想将所有DOM引用存储在对象中,但是它必须是字符串,因为DOM稍后会创建。 Later I would like to use function to add "click" events to all stored selectors, problem is that no matter what I would try I can't convert them to proper jQuery objects somehow. 后来我想使用函数向所有存储的选择器中添加“单击”事件,问题是无论我如何尝试,我都无法以某种方式将它们转换为正确的jQuery对象。 Classic $(...) seems not to work, and I don't know what's going on. 经典$(...)似乎不起作用,我不知道发生了什么。 I get "TypeError: a is not an object" now, with previous tries i had "b is undefined" and so on. 我现在收到“ TypeError:a不是对象”,以前的尝试中我有“ b未定义”,依此类推。

How to fix that ?? 如何解决?

  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> 

The value of this is not exactly string. this是不完全的字符串。 It is a object and you need to convert it to string. 它是一个对象,您需要将其转换为字符串。

console.log(typeof this) // object
console.log(this + '');  // String ".image"
var item = $(this + ''); // works
console.log(item); // now you have jquery object

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM