我对Javascript比较陌生,所以我可能会犯一些错误。我正在尝试编写一些删除新列表项的简单javascript。当运行不同的javascript函数时,新的列表项本身是动态创建的。这是代码:
$(document).ready(function () {
str_to_append = '<li class="list-group-item"> <form method="POST" action="www.example.com" accept-charset="UTF-8" class="qty-form form-inline col-xs-9"><input name="_method" type="hidden" value="PATCH"><input name="_token" type="hidden" value="hglVSLGEqDVUpGw2RWq6qfAgcwzNg5vVquYRaevm"> <input class="col-xs-6" name="name" type="text" value=""> <span class="pull-right col-xs-6"> <input type="button" class="down col-xs-3" value="-" data-min="0"/> <input class="col-xs-3" maxlength="2" name="quantity" type="text" value="0"> <input type="button" class="up col-xs-3" value="+" data-max="50"/> <input type="submit" class="submit col-xs-3" value="✅" name="submit"/> </span> </form> <span class="col-xs-3 delete"> <input type="submit" class="close-create col-xs-4" value="✕" name="delete"/> </span> </li>';
$(".addRow").on('click',function(){
$("#foodItemRows").append(str_to_append);
});
$(".close-create").on('click',function(){
alert("This worked?");
//$("#new-create").remove();
});
});
小提琴:http://jsfiddle.net/nobisnews/v0hpbtqj/1/
当我删除第一个('click',function(){....}时,它可以正常工作。如,
$(document).ready(function () {
str_to_append = '<li class="list-group-item"> <form method="POST" action="www.example.com" accept-charset="UTF-8" class="qty-form form-inline col-xs-9"><input name="_method" type="hidden" value="PATCH"><input name="_token" type="hidden" value="hglVSLGEqDVUpGw2RWq6qfAgcwzNg5vVquYRaevm"> <input class="col-xs-6" name="name" type="text" value=""> <span class="pull-right col-xs-6"> <input type="button" class="down col-xs-3" value="-" data-min="0"/> <input class="col-xs-3" maxlength="2" name="quantity" type="text" value="0"> <input type="button" class="up col-xs-3" value="+" data-max="50"/> <input type="submit" class="submit col-xs-3" value="✅" name="submit"/> </span> </form> <span class="col-xs-3 delete"> <input type="submit" class="close-create col-xs-4" value="✕" name="delete"/> </span> </li>';
$("#foodItemRows").append(str_to_append);
$(".close-create").on('click',function(){
alert("This worked?");
//$("#new-create").remove();
});
});
单击x将创建警报。但是在那里有第一个on(click)功能,它不会。感谢。
答案 0 :(得分:3)
您正在侦听尚未创建的元素上的事件。改为使用事件委托:
$("#foodItemRows").on("click", ".close-create", function(){
alert("This worked?");
//$("#new-create").remove();
});
答案 1 :(得分:1)
只需替换以下代码
$(".addRow").on('click',function(){
$("#foodItemRows").append(str_to_append);
});
以下
$("#foodItemRows").append(str_to_append).on('click','.close-create',function()
{
alert('hello');
})
答案 2 :(得分:0)
您应该在追加html之后添加事件监听器,因为该元素尚不存在。
$(".addRow").on('click',function(){
var a = $("#foodItemRows").append(str_to_append);
a.find(".close-create").on('click', function(){
alert("This worked?");
//$("#new-create").remove();
});
});