简体   繁体   中英

Can't use jQuery function inside Object Literal

I'm trying to learn how the object literals pattern works in Javascript. In one of my projects i'm stuck on a part where I use some jQuery functions. 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.

HTML: Some parts with a remove button. When clicked, I want to display an alert with the associated id extracted as data-attribute from the DOM. But there is the part it is failing, javascript does not know what .data means in that specific function.

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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