在这里用这个简单的代码确实很费劲。我正在检查带有#setactionsuccess的部分是否存在,如果不存在,我想创建它并将其添加到容器中。第一部分工作正常,但从不进行其他操作(并且满足条件-我对此进行了三重检查)。任何帮助,不胜感激。

if ($('#setactionsuccess')){
    var currenttime = new Date();
    $('#setactionsuccess').empty();
    $('#setactionsuccess').html('<h2>Set successfully deleted</h2><p>Set was successfully removed from this Edition on '+currenttime+'</p>');
} else {
    console.log('here');
    var string = '<section class="successful" id="setactionsuccess"><h2>Set successfully deleted</h2><p>Set was successfully removed from this Edition on '+currenttime+'</p></section>';
    console.log(string);
    $('#currentsets').prepend(string);
}

最佳答案

if ($('#setactionsuccess'))始终返回true
因为nullundefined和jquery的javascript校验永远不会返回nullundefine d,即使存在任何id为setactionsuccess的元素
尝试寻找选择器$('#setactionsuccess').length的长度

关于jquery - 如果/否则在jQuery中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11901435/

10-09 18:11