当我运行如下所示的 jQuery 时,previousDiv 的值始终是:[]。我尝试了 .prev() 函数的几种变体,包括 .prev('div') 和 .prev(),结果都相同。
这是jQuery:
$('.AddToRole').click(function(evt) {
var path = document.URL;
var thisUser = this.value;
var previousControl = $(this).prev('.AvailableRoles');
var newUserRole = previousControl[0].options[previousControl[0].selectedIndex].text;
var newHTML = "<button id='button_DeleteRole_" + newUserRole +"' class='DeleteRole' value=" + newUserRole + ">X</button> <label id='label_DeleteRole_" + newUserRole + "'>" + newUserRole + "</label><br />";
var previousDiv = $(this).prev('#DisplayUserRoles');
$(previousDiv).append(newHTML);
这是页面中的 html/razor 代码:
<div>
@* Display user email. *@
<h3>@user.Email</h3>
<div>
<div id="DisplayUserRoles">
@{
@* Display roles user belongs to. *@
foreach (var role in userRoles)
{
@* Remove user from role button. *@
<button id="button_RemoveFromRole_@user.Email" value="@role.RoleName" onclick="RemoveUserFromRole(this);">X</button>
<label id="label_RemoveFromRole_@role.RoleName">@role.RoleName</label>
<br />
}
}
</div>
<br />
@{
@* Create ListBox with roles user does not belong to. *@
var items = rolesUserDoesNotBelongTo.Select(i => new SelectListItem
{
Value = i.RoleName,
Text = i.RoleName
});
string listBoxId = "listboxRoles_";
listBoxId = listBoxId + user.Email;
}
@Html.ListBox(listBoxId, items, new { @class = "AvailableRoles" })
@* Add user to role button. *@
<button id="button_AddToRole_@user.Email" class="AddToRole" value="@user.Email">Add To Role</button>
</div>
</div>
对于最终结果,我试图在#DisplayUserRoles 的结束 div 标记之前添加另一个按钮和标签。