0

我尝试了以下代码,其中我遇到了问题<li>,它是由 jquery 动态插入的,Click 事件<li>根本没有触发。

我应该使用.on()or.delegate()吗?

代码

<!DOCTYPE html>
<html>
<head>
<script type=text/javascript     src=http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js></script>
<script type=text/javascript>
$(document).ready(function(){
$("ul li").on("click",function(){
    alert("hi");

});
$(":button").click(function(){
    var ul=$("ul");
    var txt=$(":text").val();
    ul.append("<li>" + txt + "<button>X</button></li>");
});


}); 

</script>
<style>
button
{
border:none;
float:right;
width:100px;
height:100px;
background-color:white;
cursor:pointer;
font-size:30px
}
body
{
background-color:#AB19CD;

}
div
{
margin:100px auto;
width:520px;
height:100px;
text-align:center;
line-height:100px
}
input[type=text]
{
width:400px;
height:100px;
border:none;
font:300 30px/100px 'Verdana';
box-sizing:box-border;
outline:none;
padding-left:10px;
background-color:rgba(0,0,0,0.15);
float:left
}
input[type=button]
{
width:100px;
height:100px;
border:none;
font:300 30px/100px 'Verdana';
float:left
}
ul
{
list-style-type:none;
padding:0
}
li
{
float:left;
width:500px;
height:100px;
background-color:white;
text-align:left;
padding-left:10px;
font:300 30px/100px 'Verdana';
margin-top:10px
}
</style>
</head>
<body>
<div>
<input type=text placeholder=Password><input type=button value=Add>
<ul></ul>
</div>

</body>
</html>

请帮我找到答案

4

1 回答 1

1

您快到了。改变

$("ul li").on("click",function(){
    alert("hi");
});

$("ul").on("click", "li" ,function(){
    alert("hi");
});

这种方式你是静态ul的将点击事件委托给li.

于 2013-07-27T16:53:23.903 回答