在 if 条件不起作用的情况下使用 .hasClass()

Using .hasClass() in if condition is not works

本文关键字:hasClass 情况下 if 条件 不起作用      更新时间:2023-09-26

当用户将鼠标悬停在它上面时,我有一个div,它会插入一个div childdiv。但是问题在于每次悬停时,它都会重复添加相同的div。所以我尝试了下面的脚本来检查childdiv 是否可用MotherDiv什么都不做。否则添加Childdiv。这些都发生在悬停时。那么,下面的代码有什么问题呢?

我错过了什么吗?

if ($('.MotherDiv').hasClass('Child'))
{
alert('alerady a div there!');//DO NOTHING
}
else 
 {        
 var Details= "<div class='MotherDiv'><table class='Special'><tr><td>Offers</td></tr><tr><td>CheckOut Now</td></tr></table></div>";
  $(Child).insertAfter($(this));//This is insert the child div on hover
}
上面

显示的JavaScript截图无效。你不能像那样有换行符。

您可以在行尾添加一个',以表示它继续,但它通常被视为一种不好的做法。

if ($('.MotherDiv').hasClass('Child')) {
    alert('alerady a div there!');//DO NOTHING
} else {        
    var Details= "<div class='MotherDiv'>'
       <table class='Special'>'
       <tr><td>Offers</td></tr>'
       <tr><td>CheckOut Now</td></tr>'
       </table>'
       </div>";
    $(Child).insertAfter($(this));//This is insert the child div on hover
}

请注意,'后不能有任何字符,否则会出错。

你在寻找这样的东西吗?如果div 没有,只需添加新的子类。如果您需要在母div 中添加新的子div,那么您只需要稍微自定义一下代码即可。

http://jsfiddle.net/ETuZB/3/

问题可能是您有一个跨多行的字符串。
JavaScript 不会以这种方式处理字符串。 您需要将字符串分成几部分并将它们连接"..." + "...",或者使用行终止转义'来保留换行符和后面的空格。

var Details= "<div class='MotherDiv'>
 <table class='Special'>
   <tr><td>Offers</td></tr>
   <tr><td>CheckOut Now</td></tr>
 </table>
 </div>";

自:

var Details = "<div class='MotherDiv'>"
            + "<table class='Special'>"
            + "<tr><td>Offers</td></tr>"
            + "<tr><td>CheckOut Now</td></tr>"
            + "</table>
            + "</div>";

或:

var Details = "<div class='MotherDiv'>              '
                  <table class='Special'>           '
                     <tr><td>Offers</td></tr>       '
                     <tr><td>CheckOut Now</td></tr> '
                   </table>                         '
                </div>";

假设这是您要生成的 HTML 结构:

<div class="Mother">
    Mother Div Content
    <div class="Child">
        Child Div to be generated dynamically
    </div>
</div>

jQuery 脚本:

$(".Mother").hover(function(){
    var motherDiv = $(this);
    if(motherDiv.find(".Child").length == 0) {
        var childDiv = $("<div class='Child'>Child Div Content</div>");
        motherDiv.append(childDiv);
    }
});
$(function(){
    var $motherDiv=$('.MotherDiv');
    $motherDiv.bind('mouseenter',
    function(){
        if($motherDiv.find('.ChildDiv').length==0){
            $('<div></div>',{class:'ChildDiv',text:'Child Data Text'}).appendTo($motherDiv);
        }
    });});
.MotherDiv

添加到文档中的什么位置? 您似乎没有插入$(Details).