on click事件只运行一次

时间:2016-08-06 10:10:46

标签: javascript jquery

当我点击加号时,我想添加图像和文本框,当点击mynasicondiv删除图像和文本框。我的问题是下次我点击plusiondiv没有添加图像和文本框。只有刷新页面,然后单击加号。

$(function () {
    $('.plusicondiv').on('click', function () {
        
        var textBox = '<input type="text" class="textbox"/>';
        
        $('.box').append(textBox);
        
        
        var img = '<img class="mynasicondiv" src="vectorimages/mynas.svg"></img>';

        $('.box').append(img);
        
  
    $(function() {
        $(".mynasicondiv").on("click", function () {
            $(this).parent(".box").remove();
         return
        })
    });
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

4 个答案:

答案 0 :(得分:5)

使用$(document).on点击动态生成的dom元素事件

 $(document).on('click','.mynasicondiv',function () {
                $(this).parent(".box").empty();
             return
 })

如果删除()box div,则无法追加img。最好使用empty()清除内部孩子的.box容器

  

所有代码

$(function () {
    $('.plusicondiv').on('click', function () {

        var textBox = '<input type="text" class="textbox"/>';

        $('.box').append(textBox);


        var img = '<img class="mynasicondiv" src="vectorimages/mynas.svg"></img>';

        $('.box').append(img);


    $(function() {
        $(document).on("click",".mynasicondiv",function () {
            $(this).parent(".box").empty();
         return
        })
    });
    });
});

答案 1 :(得分:1)

您在另一个内部使用integer一个不需要的内容。

此处$(function() { ...})是动态创建的元素。所以委托附加的事件。

$(".mynasicondiv")

注意:您要删除$(function() { $('.plusicondiv').on('click', function() { var textBox = '<input type="text" class="textbox"/>'; $('.box').append(textBox); var img = '<img class="mynasicondiv" src="vectorimages/mynas.svg"></img>'; $('.box').append(img); }); $("body").on("click", '.mynasicondiv', function() { $(this).parent(".box").remove(); return }) }); ,因此下次无法追加.box,因为textBox不会出现在DOM中

答案 2 :(得分:0)

您正在完全删除.box div,这就是您无法添加其他输入和图像的原因。而是这样做:

&#13;
&#13;
$('.plusicondiv').on('click', function() {
    var textBox = '<input type="text" class="textbox"/>';
    $('.box').append(textBox);
    var img = '<img class="mynasicondiv" src="https://placehold.it/350x150"></img>';
    $('.box').append(img);
});
$("body").on("click", ".mynasicondiv", function(e) {
    $(this).parent(".box").html('');
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box">
</div>
<div class="plusicondiv">
    click me
</div>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

我认为您希望功能在点击时添加更多新字段。我建议使用下面的jQuery插件。 [http://www.mdelrosso.com/sheepit/][1]

在您的代码中,您可以替换

代替
$(this).parent(".box").remove();

以下代码

$(this).(".box").html('');

因为remove()函数删除了所有的框类html

相关问题