使用JQuery基于条件删除元素

时间:2013-01-21 14:03:04

标签: javascript jquery

<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不会删除它。

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

谢谢你的进步!

4 个答案:

答案 0 :(得分:3)

$('#this')应该是$(this)$('#this')匹配带有id=this的元素

答案 1 :(得分:3)

除非您确实拥有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');
    }
});

答案 2 :(得分:0)

使用此:

<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

答案 3 :(得分:0)

需要注意的一点是,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。 (并且不要忘记让这些变量名称是唯一的。)