[英]Can't use jQuery function inside Object Literal
我正在嘗試學習對象文字模式在 Javascript 中是如何工作的。 在我的一個項目中,我被困在我使用一些 jQuery 函數的部分。 為了這個問題,我建立了一個小例子。
我希望有人能給我提供一些很棒的提示。
Javascript:創建一個對象字面量,並調用 init() 方法。
HTML:一些帶有刪除按鈕的部分。 單擊時,我想顯示一個帶有從 DOM 中提取為數據屬性的關聯 id 的警報。 但是有一部分失敗了,javascript 不知道 .data 在該特定函數中的含義。
謝謝... !
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.