这是我的HTML文件的一部分;
<script type="text/template" id="_profile">
<div class="modalDialog">
<div class="profile">
<div class="box clearfix">
<div class="box-header clearfix">
<span class="box-title l">{% trans 'PROFILE' %}</span>
<a href="#" style="margin-left: 10px;" id="profile_export" class="l"><span class="icon-download"></span>{% trans 'Profile Export' %}</a>
<div class="close-profile icon-cancel-circled r"></div>
</div>
Run Code Online (Sandbox Code Playgroud)
和
$('.profile').on('click', '#profile_export', function (e) {
e.preventDefault();
$.get(root + '/profile/export/', function(resp) {
// DO something
Run Code Online (Sandbox Code Playgroud)
我已经看了一些"jQuery中的事件委托"的例子,所以我写了上面的函数.可能是错的,因为当我点击它时,它什么也没做.它只是放在#当前URL的末尾.
谁能告诉我这里有什么问题?为什么当我点击#profile_export它不会触发"profile/export /"的请求?
谢谢
您使用.profile主要选择器是问题所在.您需要将委派的事件处理程序挂钩到页面加载时DOM中的元素.例如:
$(document).on('click', '#profile_export', function (e) {
e.preventDefault();
// your code...
});
Run Code Online (Sandbox Code Playgroud)
请注意,document这只是为了举例.理想情况下,您应该使用最接近的元素,在这种情况下,我会将其视为您要附加_profile模板的元素.