ajax请求动态生成dmo无法绑定事件解决方案

Posted 客官不爱喝酒

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ajax请求动态生成dmo无法绑定事件解决方案相关的知识,希望对你有一定的参考价值。

因为使用ajax:是不会刷新dom元素结构的,我怎么绑定事件都不生效,用jquery的on也不行,后来用行内事件绑定的方式终于搞定了。

1.前端代码

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Bootstrap 实例 - 带语境色彩的面板</title>
    <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script src="../js/axios2.1.js"></script>
    <script src="../js/vue2.6.js"></script>
</head>
<style>
    #list{
        margin-left: 20%;
    }
    ul {
        list-style-type: none; margin:0;padding: 10px;
    }
    #list ul li{
        float: left; margin-left: 50px;
    }
    .panel-heading{
        margin:0;padding: 0px; height: 35px;
    }
</style>
<body>

<div class="container" id="app">
    <div class="col-lg-8 col-of col-lg-offset-2" style="margin-top: 5%">
        <div class="panel panel-primary" >
            <div class="panel-heading">
                <button class="btn btn-success pull-right"  id="add" data-toggle="modal" data-target="#myModal">添加愿望</button>
                <h3 class="panel-title text-center">许愿墙</h3>

            </div>
             <!-- 请求回来的数据放到:content中  -->
            <div id="content" >

            </div>
        </div>
    </div>
</div>
</div>


<div id="list">
    <ul>
        <li><button class="btn btn-success " >下一页</button></li>

        <li><button class="btn btn-success " style="margin-left: 600%"  >上一页</button></li>
    </ul>
</div>



<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                <h4 class="modal-title text-success text-center" id="myModalLabel" >修改愿望</h4>
            </div>
            <div>
                <form class="form-horizontal" role="form" action="../php/add.php" method="post">
                    <div class="form-group">
                        <label class="col-sm-2 control-label">id</label>
                        <div class="col-sm-10">
                            <input type="text" maxlength="5" minlength="5" name="id" id="id" class="form-control" placeholder="请输入id号">

                        </div>

                    </div>
                    <div class="form-group">
                        <label  class="col-sm-2 control-label">姓名</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control"   maxlength="8" minlength="2" name="name" id="name" placeholder="请输入姓名">

                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">颜色</label>
                        <div class="col-sm-10">
                            <input type="color" class="form-control" maxlength="1" minlength="1" name="color" id="color">

                        </div>
                    </div>
                    <div class="form-group">
                        <label  class="col-sm-2 control-label" >内容</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" minlength="1" maxlength="3" name="content" id="context"  placeholder="请输内容">

                        </div>
                    </div>
                    <div class="form-group">
                        <label  class="col-sm-2 control-label" >密码</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" minlength="1" maxlength="3" name="password" id="password"  placeholder="请输密码">

                        </div>
                    </div>


                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                        <button type="submit" class="btn btn-primary"  >提交更改</button>
                    </div>
                </form>
            </div>

        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

<script>
    $(function () {
        // 显示数据
        $.ajax({
            url: "../php/ajax.php",
            type: "json",
            method:"post",
            success: function(data){
             var result=data.rows;
             console.log(data);
             var html = "";
             for (var i=0;i<result.length;i++){
                 console.log(result[i].id+","+result[i].name+","+result[i].color+","+result[i].content+","+result[i].password+","+result[i].time);

                   html+="   <div class='panel-body' >" +
                       "                    <ul>" +
                       "                        <li>id:"+result[i].id+"</li>" +
                       "                        <li>名字:"+result[i].name+"</li>" +
                       "                        <li>内容:"+result[i].content+"</li>" +
                       "                        <li>时间:"+result[i].time+"</li>" +
                       "                    </ul>" +
                       "                    <button class='btn btn-danger del' οnclick='deletes("+result[i].id+")' id='delete' data-id='"+result[i].id+"' >删除愿望</button>" +
                       "                    <button class='btn btn-primary ' data-toggle='modal' data-target='#myModal'>修改愿望</button>" +
                       "                    <hr>" +
                       "      </div>"
                 
             }
                $("#content").append(html);
            }
        });
    });

    function deletes($id) {
        alert($id);
    }
</script>

</body>
</html>

2.后端代码

<?php

header('Content-Type:application/json');

try {

$conn = new PDO("mysql:host=localhost;dbname=student", 'root', 'admin');

    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $conn->exec("SET NAMES utf8");

} catch (PDOException $e) {

 echo "conn_error:<br/>" . $e->getMessage();

}

$sql = "select id, name, color, content, password, time from php_wish limit 0,2";

$result = $conn->query($sql)->fetchAll(PDO::FETCH_ASSOC);

$json['total'] = count($result);

$json['rows'] = $result;

echo json_encode($json, JSON_UNESCAPED_UNICODE);


解决方案:使用行内绑定事件

<button class=' del' onclick='deletes("+result[i].id+")' id='delete' data-id='"+result[i].id+"' >删除愿望</button>
    function deletes($id) {
        alert($id);
    }

在这里插入图片描述

在这里插入图片描述

以上是关于ajax请求动态生成dmo无法绑定事件解决方案的主要内容,如果未能解决你的问题,请参考以下文章

给按钮绑定的click事件无效

ajax动态刷新的元素,导致绑定事件失效

在js中怎么给动态生成的元素绑定事件

解决jQuery ajax动态新增节点无法触发点击事件的问题

在由 AJAX 插入的动态创建元素上绑定事件(复选框)

动态生成标签并绑定带参数事件