[英]JQuery not appending <li> items to a <ul> list
問題背景:
我有一個MVC網站,我正在將對象列表傳遞給視圖,然后該視圖應以編程方式為列表中的每個項目建立一個下拉列表。
我正在嘗試構建一個如本示例所示的項目下拉列表( 請注意-這是一個示例,並非來自我的網站 ):
問題:
我遍歷對象列表,將每個對象傳遞給稱為“ AddRows”的腳本方法。 我可以看到正在傳遞項目,但無法將項目追加到列表(ID為CartList)中。
編碼:
ID為CartList
的HTML
<ul class="dropdown-menu cart-content" id="CartList" role="menu">
</ul>
Razor Foreach
遍歷傳遞的對象列表並調用提供相關屬性的AddRow
方法:
@foreach (var cartItem in (List<LoginTest.Models.CartItem>)ViewBag.Data)
{
<script>
var cartItemName = '@cartItem.CartItemName';
var cartItemQty = '@cartItem.CartItemQty';
var cartItemPrice = '@cartItem.CartItemPrice';
AddRows(cartItemName, cartItemQty, cartItemPrice)
</script>
}
AddRows方法,該方法應將新列表項追加到CartList
列表。
<script type="text/javascript">
var AddRows = function (productName, productQty, productPrice) {
$('#CartList').append('<li><b>' + productName + '</b><span>x ' + productQty + ' £' + productPrice + '</span></li>');
};
</script>
任何幫助,將不勝感激。
這是有效的示例鏈接
http://jsfiddle.net/nadeemmnn2007/8jt5ce6g/2/
HTML
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown" aria-expanded="true">
Dropdown
<span class="caret"></span>
</button>
<ul id="CartList" class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1">
</ul>
</div>
JS
var AddRows = function (productName, productQty, productPrice) {
$('#CartList').append('<li><b>' + productName + '</b><span>x ' + productQty + ' £'+ productPrice + '</span></li>');
};
for(i = 0; i < 10 ; i++)
{
AddRows('test',''+i+'','100');
}
您可以將集合直接分配給javascript變量,而不用所有這些額外的內聯腳本來污染html。
<script>
$(function() {
var items = JSON.parse('@Html.Raw(Json.Encode(ViewBag.Data))');
var cartList = $('#CartList');
$.each(items, function(index, item) {
var li = $('<li></li>');
li.append($('<b></b>').text(item.CartItemName));
li.append($('<span></span>').text('x ' + item.CartItemQty + ' £' + item.CartItemPrice));
cartList.append(li);
});
});
</script>
但是,通過使用ChildAction
將菜單作為部分視圖返回並在主視圖中使用@Html.Action(...)
,可以輕松完成所有這些操作,而無需使用javascript
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.