0

我得到了 JSON 数组格式的 Ajax 调用的结果,像这样

var productList ={
"products": [
    {
        "brandName": "B1",
        "productID": "Pid1",
        "productName": "P1",
        "imagePath": "IP1",
        "mrp price": "9.99",
        "sell price": "8.99"
    },
    {
        "brandName": "B1",
        "productID": "Pid3",
        "productName": "P2",
        "imagePath": "IP2",
        "mrp price": "19.99",
        "sell price": "18.99"
    },
    {
        "brandName": "B1",
        "productID": "Pid3",
        "productName": "P4",
        "imagePath": "IP1",
        "mrp price": "29.99",
        "sell price": "558.99"
    }
]
};

现在在 ajax 调用的成功函数中,我想为<li> .. </li>JSON 响应中可用的每个产品创建元素。我想将一些 CSS 类和 Id 应用于元素。这是 li 的格式。

<li class='productWrap $productID' style='height:200px; width:150px;'>
<center> 
    <div class=\"productImageWrap\" id=\"productImageWrapID_+$productID\">
        <img src=$imagePath width='75' height='75' />
    </div>
    <div>
        <div style='font-size: 11px; font-family: \"Verdana\"; '> 
            $brandName + " " + $productName 
        </div>
        <b>                             
            <span>  
                <strike>   $mrp price  </strike>    
                $sell price 
            </span>
            <a href='#' id=\"featuredProduct_$data[0]\" onclick=\" adjust_menu(this.id); simpleCart.add('name=$brandName + " " + $productName', 'price=$sell price','image=$imagePath');             return false;\">   
                <img src='images/add-to-basket2.gif' alt='Add To Basket' width='111' height='32' id='featuredProduct_+$productID' />
            </a>
        </b>
    </div>
</center>
</li>

我的疑问是如何在 Ajax 成功函数中填充这些值。我需要填充的值显示为 $ 前缀,如 $brandName $productName 等。

我不仅想要填充这些值以显示,而且想要填充这样一种方式,即我可以在填充后访问任何元素(使用我们在填充时应用的 CSS 类和 ID)以用于 Jquery 单击和鼠标悬停功能.

4

1 回答 1

2

你可以做类似的事情

   success: function(data){
         $ul = $('#theUl');
         data.products.each(function(){
             var li = "<li><h1 class='name'>"+this.brandName+" "+this.productName+"</h1></li>";
             $ul.append(li);
         });

   }

另外,如果你想在 h1.name 上有一个点击事件,你必须委托选择器,因为你在它准备好之后将它推送到 DOM 中。这可能看起来像:

$(document).on("click",".name",function(){
  alert('Yeah i successfully bound an event with an element that did not exist initially')
});
于 2013-11-14T10:17:26.560 回答