<a href="" preventdefault="" works="" every="" second="" time=""

时间:2018-04-04 13:03:38

标签: javascript jquery html

="" I have a trash icon which user clicks on to delete current element from database. I want to make it work with ajax if user has javascript enabled. There are multiple items on page.

Don't know why but even after adding preventDefault, href works like regular href instead of performing ajax. It triggers ajax request without refreshing window only every second time I click on trash icon.

Do you know where is the problem?

$('.delete_bulletin').on('click', function (e) {
    console.log('event');
    e.preventDefault();
    $.get($(this).attr('href')).done(
            function () {
                reloadBoardContent();
            }
    );
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="bulletin_board">
    <div class="bulletin_card">
        <i>4. apríl 2018 14:50</i>
        <h4>NAME</h4>
        <p></p><p>htrhr</p><p></p>
        <a class="delete_bulletin" href="/bulletin-board/delete/35/"><img style="max-height: 20px" src="/static/bulletin_board/icons/trash.png"></a>
    </div>
    <hr>
    <div class="bulletin_card">
        <i>4. apríl 2018 14:49</i>
        <h4>NAME</h4>
        <p></p><p>fdsafdfs</p><p></p>
        <a class="delete_bulletin" href="/bulletin-board/delete/34/"><img style="max-height: 20px" src="/static/bulletin_board/icons/trash.png"></a>
    </div>
    <hr>
</div>

1 个答案:

答案 0 :(得分:6)

我非常确定(但需要确认)您的reloadBoardContent()正在更新此div所在的<a>

如果是这种情况,锚将被替换,事件不会触发新创建的。

解决方案是使用委托事件,这将使其适用于动态添加的元素。

请改为:

$('#bulletin_board').on('click', '.delete_bulletin', function (e) {

如果你不替换<div id="bulletin_board"本身而只替换它的内容,从现在开始一切都会好起来。