if / else在jquery中

时间:2012-08-10 12:12:38

标签: jquery

这里真的很难用这个简单的代码。我正在检查是否存在#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);
}

6 个答案:

答案 0 :(得分:5)

试试这个

if($('#setactionsuccess').length > 0)

答案 1 :(得分:1)

即使没有匹配项,您也会从选择器中获得一些东西。你要检查0的匹配数。

答案 2 :(得分:1)

您可以使用length

检查元素是否存在
if($('#setactionsuccess').length) {
   ...
}

答案 3 :(得分:1)

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

的长度

答案 4 :(得分:0)

如果你总是拥有身份#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);
}

答案 5 :(得分:0)

if ($(selector).length)

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