[英]PreventDefault not working for dynamic link
<a href="#" class="submit-form show-field" data-show-field="#Product" >View products</a>
此鏈接是動態添加到dom的,點擊時會觸發jQuery函數
$('body').on("click", 'a.show-field', function(e) {
if (!$(this).attr('data-show-field')) {
return;
}
$($(this).attr('data-show-field')).parent().show();
e.preventDefault();
});
事件觸發正常,但頁面重定向。 我不明白我做錯了什么
您必須先觸發事件,然后才能阻止它。
$('body').on("click", 'a.show-field', function(e) {
e.preventDefault();
if (!$(this).attr('data-show-field')) {
return;
}
$($(this).attr('data-show-field')).parent().show();
/*e.preventDefault(); */
});
如果頁面重定向,那么我認為您的監聽器運行不正常。 在這里,您是一個具有用例的小伙伴。 准備好文件
我不知道您將代碼放在哪里,但是如果它不在“文檔准備就緒”之外,則偵聽器永遠不會觸發。
$('body').on("click", 'a.show-field', function(e) {
alert("First attemp is attached");
});
$(document).ready(function() {
$('body').on("click", 'a.show-field', function(e) {
alert("Second attemp is attached");
if (!$(this).attr('data-show-field')) {
return;
}
$($(this).attr('data-show-field')).parent().show();
e.preventDefault();
});
});
PD:對不起,我的英語
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.