简体   繁体   English

不能在 Object Literal 中使用 jQuery 函数

[英]Can't use jQuery function inside Object Literal

I'm trying to learn how the object literals pattern works in Javascript.我正在尝试学习对象文字模式在 Javascript 中是如何工作的。 In one of my projects i'm stuck on a part where I use some jQuery functions.在我的一个项目中,我被困在我使用一些 jQuery 函数的部分。 For the sake of the problem I build a little example.为了这个问题,我建立了一个小例子。

I hope someone can provide me with some awesome hints.我希望有人能给我提供一些很棒的提示。

Javascript: creating an object literal, and calling the init() method. Javascript:创建一个对象字面量,并调用 init() 方法。

HTML: Some parts with a remove button. HTML:一些带有删除按钮的部分。 When clicked, I want to display an alert with the associated id extracted as data-attribute from the DOM.单击时,我想显示一个带有从 DOM 中提取为数据属性的关联 id 的警报。 But there is the part it is failing, javascript does not know what .data means in that specific function.但是有一部分失败了,javascript 不知道 .data 在该特定函数中的含义。

Thanks... !谢谢... !

 var test = { init: function() { this.dom(); this.events(); }, dom: function() { this.$contentbox = $('.box'); this.$buttons = this.$contentbox.find('a'); }, events: function() { this.$buttons.on('click', this.removeDiv); }, removeDiv: function(event) { event.preventDefault(); var div = this.closest('.removeMe'); // This works perfectly var divID = div.data('id'); // Crashing -> Uncaught TypeError: div.data is not a function alert('Product ' + divID + ' is to be deleted...'); } } test.init();
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="box"> <div class="content"> Hi there! Click X to delete item :) </div> <div data-id="6" class="removeMe"> Product 6 <a href="#">(X)</a> </div> <div data-id="7" class="removeMe"> Product 7 <a href="#">(X)</a> </div> <div data-id="8" class="removeMe"> Product 8 <a href="#">(X)</a> </div> </div>

div是一个HTMLDivElment不是一个 jQuery 对象,所以没有.data()方法,而是:

var divID = $(div).data('id')

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

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