perhaps? 2015-01-02 10:31 采纳率: 100%
浏览 25

jQuery脚本将无法正常工作

This question already has answers here:
                </div>
            </div>
                    <div class="grid--cell mb0 mt4">
                        <a href="/questions/203198/event-binding-on-dynamically-created-elements" dir="ltr">Event binding on dynamically created elements?</a>
                            <span class="question-originals-answer-count">
                                (23 answers)
                            </span>
                    </div>
            <div class="grid--cell mb0 mt8">Closed <span title="2015-01-02 10:36:30Z" class="relativetime">5 years ago</span>.</div>
        </div>
    </aside>

I have the following setup for a community website:

<div id="posts">
    <div class="container">
        <div id="placeholder"></div>
        <h1>Friend Requests</h1>
    </div>
</div>

getRequests.js appends the following into the container div:

<div id="4" class="result">
    <a href="user.php?id=4">
        <img src="images/user-uploads/profile/?id=4">Random Guy
    </a>
    <div class="response">
    <button data-id="4" class="accept">Accept</button>
    <button data-id="4" class="deny">Deny</button>
    </div>
</div>

friendResponse.js has the following:

$(function(){
  $(".accept").click(function(){
    var id = $(this).attr("data-id");
    $("#"+id).remove();
  });
});

So, you would expect that when I click the accept button, the container with id=1 should get removed, but for some reason, it doesn't.

And also, to add to the peculiarity, the code works if I inject it through the console.

And, for the record, the script is not showing any errors.

</div>
  • 写回答

1条回答 默认 最新

  • ℙℕℤℝ 2015-01-02 10:36
    关注

    Try:

    $(function() {
      $(document).on("click", ".accept", function() {
        var id = $(this).data("id");
        $("#"+id).remove();
      });
    });
    

    Explanation:

    You have to set the event for all new incoming node .accept. You have to bound the event on the document. See live event.

    Here is the corresponding jsfiddle

    评论

报告相同问题?

悬赏问题

  • ¥20 删除和修改功能无法调用
  • ¥15 kafka topic 所有分副本数修改
  • ¥15 小程序中fit格式等运动数据文件怎样实现可视化?(包含心率信息))
  • ¥15 如何利用mmdetection3d中的get_flops.py文件计算fcos3d方法的flops?
  • ¥40 串口调试助手打开串口后,keil5的代码就停止了
  • ¥15 电脑最近经常蓝屏,求大家看看哪的问题
  • ¥60 高价有偿求java辅导。工程量较大,价格你定,联系确定辅导后将采纳你的答案。希望能给出完整详细代码,并能解释回答我关于代码的疑问疑问,代码要求如下,联系我会发文档
  • ¥50 C++五子棋AI程序编写
  • ¥30 求安卓设备利用一个typeC接口,同时实现向pc一边投屏一边上传数据的解决方案。
  • ¥15 SQL Server analysis services 服务安装失败