使用JQuery根据条件删除元素

Deleting elements based on condition with JQuery

本文关键字:删除 元素 条件 JQuery 使用      更新时间:2023-09-26
<input id="img" type="file" name="img" accept="image/*">

这是JQuery代码:

$('#img').change(function(){
    if($('#this').val() === '') { 
        $("#subm").remove();
    }  else {
         $('<button id="subm" type="submit">Press</button>').insertAfter('#advice');
   }
});

我试着检查input file是否为空,如果是空的,并且存在一个名为subm的按钮,我删除它,但如果input file有一个文件,我创建那个底部。问题是,如果有一个subm按钮,因为我选择了文件,在我改变input之后,让它为空,JQuery不会删除它。

如果input file为空,我如何删除JQuery创建的按钮?

谢谢的!

$('#this')应该是$(this), $('#this')id=this匹配

除非您确实有一个id为"this"的元素,否则您可能打算使用this关键字来代替:

$('#img').change(function(){
    // this will be the #img that fired the change event
    if($(this).val() === '') {
        $("#subm").remove();
    }  else {
         $('<button id="subm" type="submit">Press</button>').insertAfter('#advice');
    }
});

使用

<input id="img" type="file" name="img" accept="image/*">
<button id="subm" type="submit">Press</button>
$('#img').change(function(){
    if(!this.value) { 
        $("#subm").hide();
    } else {
        $("#subm").show();
    }
}).change(); // trigger event to init

需要注意的一点是,this的值也可以根据javascript和jQuery使用的上下文而改变。现在应该没问题了,但是在更复杂的情况下,您可能会遇到问题

对于这种情况,最佳实践是立即创建另一个变量,通常称为self
$('#img').change(function () {
    var self = this;
    // self will now ALWAYS be the #img that fired the change event.
    if ($(self).val() === '') {
        $("#subm").hide();
    } else {
        $("#subm").show();
    }
});

如果您使用另一个较低的函数,那么this现在将引用较低函数中的this,则会发生问题。每当进入新函数时,为self定义一个新变量,以便始终锁定this是什么。(别忘了变量名要唯一)