2016-10-04 31 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

相关问题