1

我正在使用 ajax 来动态填充菜单。问题是动态创建的元素不遵循 CSS 规则,尽管它们是使用正确的类名创建的。这是令人惊讶的。

这是我的 HTML:

<div id='menu1'>
<ul class='menu'>
<?php
$sql = /// /* some sql  string, which works */
$result = mysql_query($sql);
    while($row = mysql_fetch_array( $result ))
    {
        $prod_id = $row['product_id'];      
        $prod_name = $row['product_name'];      
        echo "<li data-title='$prod_id' class='menu1_item'>".$prod_name."</li> ";
    }
?>
</ul>
</div>

<div id='menu2'>
<ul class='menu'>
</ul>
</div>

<div id='menu3'>
<ul class='menu'>
</ul>
</div>

这是我的jQuery:

    $(".menu1_item").click( function() {
    $.ajax({
    type: "POST",
    data: { m: '2', id: $(this).attr('data-title') },
    url: "fetch_designs.php",
    success: function(msg){
            if (msg != ''){
            $("#menu2").html(msg).show();
            $(".menu2_item").bind('click',function() {
                        $.ajax({
                        type: "POST",
                        data: { m: '3', id: $(this).attr('data-title') },
                        url: "fetch_designs.php",
                        success: function(msg){
                        if (msg != ''){
                        $("#menu3").html(msg).show();
                            }
                            }
                        });
                    //end menu2 click
                    });
                //end if
                }
            //end success
            }
        });
    //end menu1 click
    });

我的CSS如下:

ul.menu li
{
    cursor:pointer;
    list-style: none;
}

#menu1, #menu2, #menu3
{
    margin:50px;
    position:relative;
    display:block;
    float:left;
}

.menu1-item .menu2-item .menu3-item
{
    padding:4px;
    background-color:lightgray;
    color:black;
    cursor:pointer;
}

生成新菜单元素的 fetch-designs.php 中的 PHP 代码如下所示:

$nextmenu = $_POST['m'];
$id = $_POST['id'];
if($nextmenu == '2')
{
    // do something, and then finally generate new menu item as below:
    echo"<li data-title='$tpl_id' class='menu2_item' >".$tpl_name."</li> ";
    }
}
elseif ($nextmenu=='3')
{
        // do something, and then finally generate new link as below
        echo"<li class='menu3_item' ><a href='design_product.php?id=$d_id'>$d_name</a></li> ";
}
4

1 回答 1

1

您的 CSS 规则包含dash(-)但您的 js 包含underscore(_)名称class

<li data-title='$prod_id' class='menu1_item'>
                                      ^-------- underscore

.menu1-item .menu2-item .menu3-item
      ^-----------^-----------^----- but these are dash
于 2012-09-15T09:39:05.440 回答