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="http://ift.tt/1oMJErh"></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>
Aucun commentaire:
Enregistrer un commentaire