动态添加和删除输入字段jquery 1.10

时间:2014-01-22 10:13:11

标签: javascript jquery html

嗨我遇到了这个问题fiddle我发现它在1.4 jquery上运行得很好 但我使用的是Jquery的1.10版本。

我注意到{1}}方法在1.10中已弃用,因此我使用live来替换on,但仍未按预期执行。

我的小提琴是here

我过去常常编写后端代码所以请饶恕我,有人可以帮我吗?

2 个答案:

答案 0 :(得分:3)

要使on像你想要的那样工作,你需要指定一个不会被改变为主选择器的元素,并将动态元素选择器作为第二个参数传递:

$("#content").on("click", ".plus", function(){

此外,代码禁用了加号和减号按钮时出错,而不是将disabled属性设置为空,您想要将其完全删除:

parent.find(".moins").removeAttr("disabled");

最后,将.parent().parent().parent('.iteration')更改为

$(this).closest(".iteration");

因为这更简单,并且不太可能被你的html更改破坏。

http://jsfiddle.net/infernalbadger/L3s3w/3/

答案 1 :(得分:3)

您应该将parent selector $("#content")on()一起使用,并使用prop()使button disable赞成,

$("#content").on("click", ".plus",function(){
    var parent = $(this).closest(".iteration");// use closest
    parent.append('<input type="text" value="Create a task for this iteration" />');
    var nbinput = parent.find("input[type='text']").length;
    if(nbinput == 5)
        parent.find(".plus").prop("disabled",true);// use prop()
    if(nbinput > 0)
        parent.find(".moins").prop("disabled",false);
});
$("#content").on("click",".moins", function(){       
    var parent = $(this).closest(".iteration");// use closest
    parent.children("input").last().remove();
    var nbinput = parent.find("input[type='text']").length;
    if(nbinput < 5)
        parent.find(".plus").prop("disabled",false);// use prop()
    if(nbinput == 0)
        parent.find(".moins").prop("disabled",true);
});

Demo