通过jquery添加,删除记录

时间:2014-01-28 15:58:54

标签: jquery

我希望在添加项目时删除项目,但是当我点击标记范围时,它无效。

<script type='text/javascript'>
$(document).ready(function () {
    $('img#add_file').click(function () {
        $('#file_tools').before('<div class="file_upload" id="f"><input name="file[]" type="file"> <span>del</span></div>');                                             
    });
    $('span').click(function () {
        $(this).parent().hide();
    });
});
</script>

3 个答案:

答案 0 :(得分:0)

试试这个:

$(document).on("click", "span", function(){
        $(this).parent().hide();
});

提示: .on()方法可以帮助您绑定通过javascript或ajax动态创建的未来元素上的事件。

而不是$(document),最好使用$("#file_tools").parent(),或者如果您知道此父元素ID或类。

答案 1 :(得分:0)

添加像on(),bind()这样的jquery函数来点击这样的事件: -

$("span").on("click", function(){
    $(this).parent().hide();
});


$("span").bind("click", function(){
        $(this).parent().hide();
});

注意: - on(),bind()等事件可以将事件绑定到动态创建的DOM元素。

答案 2 :(得分:0)

您的代码中存在范围问题。解决方案是这样写:

<script type='text/javascript'>
$(document).ready(function () {
    $('img#add_file').click(function () {
        $('#file_tools').before('<div class="file_upload" id="f"><input name="file[]" type="file"> <span>del</span></div>');    

        // Place those instructions here!
        $('span').click(function () {
            $(this).parent().hide();
        });
    });
});
</script>

再见

相关问题