2016-10-04 68 views
1

我正在使用AngularJS動態生成大量內容的網站上工作。我需要獲取使用jQuery動態生成的元素的屬性,但我在這樣做時遇到了麻煩。我已經發現我需要使用.on方法來點擊而不是.click。我的問題是在.on方法中找到等效的$(this)jQuery在動態生成內容時獲取單擊元素的屬性

這裏是我的代碼:

$(document.body).on('click', 'a.card-topic-link' ,function(e) { 
    e.preventDefault(); // Prevent default action - this works 

    console.log('The click works!'); // This fires and works just fine 

    var cardTopicLink = $(this).attr('data-topic-link'); // This is where the problem lies 

    console.log(cardTopicLink); // This is undefined 
}); // End on click 

正如我前面所說,這並不爲.click工作動態內容不工作:

$('a.card-topic-link').click(function(e) { 
    e.preventDefault(); // Prevent default action 

    var cardTopicLink = $(this).attr('data-topic-link'); 

    console.log(cardTopicLink); 
}); 

我覺得有一個簡單的解決方案這個問題我很難找到。這個問題的關鍵是,這是處理動態內容。

讓我知道你是否有任何想法。

+0

你如何設置元素的'data-topic-link'屬性? – Frxstrem

+0

它被設置在存儲在數據庫中的HTML中,並基本上通過AngularJS打印到屏幕上。它看起來像這樣並正在正確地工作'data-topic-link =「text」'。 – mbacon40

+0

爲什麼你不使用'ng-click'並傳遞任何數據生成的屬性值呢?需要提供[mcve] – charlietfl

回答

0

事實證明,AngularJS被剝離出屬性data-topic-link爲它被解析。發生這種情況是因爲包含data-topic-link的HTML作爲Angular在ng-repeat中打印的響應的一部分被傳遞。

我更新了代碼,以便具有此屬性的HTML不需要由AngularJS提供服務。

1

使用e.currentTarget,而不是var cardTopicLink = $(this).attr('data-topic-link');,嘗試var cardTopicLink = angular.element(e.currentTarget).attr('data-topic-link');

$(document).ready(function() { 
    $(document.body).on('click', 'a.card-topic-link' ,function(e) { 
    e.preventDefault(); // Prevent default action - this works 
    console.log('The click works!'); // This fires and works just fine 

    var cardTopicLink = $(e.currentTarget).attr('data-topic-link'); // This is where the problem lies 

    console.log(cardTopicLink); 
    }); // End on click 
}); 

plunker有類似的代碼,射擊異步加載的內容 - http://plnkr.co/edit/02rqCrbBVwXiIYff8ktC?p=preview

+0

的太多未知數將會失敗,如果有任何孩子喜歡這些''內的圖標,圖像等。沒有理由'這個'不應該工作 – charlietfl

+0

你是對的,對不起,我複製了錯誤的代碼(深夜:)),我更新了我的答案和闖入者 – Andriy

相關問題