通过append添加的按钮,再通过样式获取不到

代码如下:

 <!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"> 
    <title>Bootstrap 实例 - 按钮标签</title>
    <link rel="stylesheet" href="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/css/bootstrap.min.css">  
    <script src="http://cdn.static.runoob.com/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div>
<button class="btn btn-default" type="button">按钮</button>
</div>
    <script>
        $(".btn").click(function(){
            $("div").append('<button class="alert" type="button">按钮</button>');
        })
        $(".alert").click(function(){
            alert(1);
        })
        </script>
</body>
</html>
$(".btn").click(function(){ $("div").append('<button id="alert12" class="alert" type="button">按钮</button>'); }); $('div').on('click','.alert',function(event) { alert('111'); });

说明:用bind和click只能为页面已经加载好的dom元素绑定事件,而对于动态添加的元素,可选择用delegate()/live()/on()方法来绑定事件

代码执行顺序问题,把click方法放到append后面执行就可以了

 <script>
    $(".btn").click(function(){
        $("div").append('<button class="alert" type="button">按钮</button>');
        $(".alert").click(function(){
            alert(1);
        })
    })
</script>

方法一:可以改成button的onclick的方式,
方法二:获取最后一个.alert,$('.alert').eq(总数-1).click

JQ需要入口函数的$(function() {});