1

在这里真的很努力地处理这个简单的代码。我正在检查带有#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);
}
4

6 回答 6

5

试试这个

if($('#setactionsuccess').length > 0)
于 2012-08-10T12:14:18.510 回答
1

即使没有匹配项,您也总能从选择器中获得一些东西。您必须对照 0 检查匹配数。

于 2012-08-10T12:14:33.923 回答
1

您可以通过使用检查元素是否存在length

if($('#setactionsuccess').length) {
   ...
}
于 2012-08-10T12:14:50.837 回答
1

if ($('#setactionsuccess'))总是返回 true
,因为 javascript cheks for nullandundefined和 jquery 永远不会返回 anullundefined 即使存在任何具有 id setactionsuccess dosent 的元素
尝试寻找选择器的长度$('#setactionsuccess').length

于 2012-08-10T12:16:27.303 回答
0

如果您总是有带有 id 的块#setactionsuccess并且您需要检查它是否为空,那么这是正确的解决方案:

if ($('#setactionsuccess'.text().length != 0)){
    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);
}
于 2012-08-10T12:22:20.037 回答
0
if ($(selector).length)

您可以通过此代码进行检查。

于 2012-08-10T12:28:43.157 回答