我能够检索文本字段,但是使用获取属性的剃刀语法不起作用,我试图从data-genre-id="@item.Id"
获取它时未定义
$(".dropdown-menu li")
.on('click',
function() {
$(".dropdown-toggle").text($(this).text());
var id = $(this).attr("data-genre-id");
console.log(id);
});
..
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
Dropdown
<span class="caret"></span>
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenu1">
@foreach (var item in Model.Genres)
{
<li><a data-genre-id="@item.Id">@item.Name</a></li>
}
<li role="separator" class="divider"></li>
<li><a href="#">Separated link</a></li>
</ul>
</div>
答案 0 :(得分:0)
data-genre-id
属性属于a
元素no li
,因此当您点击li
时必须找到a
元素并获取data-genre-id属性。
更改您的代码如下:
$(document).ready(function(){
$(".dropdown-menu li").on('click',function() {
$(".dropdown-toggle").text($(this).text());
var id = $(this).find("a").attr("data-genre-id");
console.log(id);
})
})
最终代码:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
Dropdown
<span class="caret"></span>
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenu1">
@foreach (var item in Model.Genres)
{
<li><a data-genre-id="@item.Id">@item.Name</a></li>
}
<li role="separator" class="divider"></li>
<li><a href="#">Separated link</a></li>
</ul>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".dropdown-menu li").on('click',function() {
$(".dropdown-toggle").text($(this).text());
var id = $(this).find("a").attr("data-genre-id");
console.log(id);
})
})
</script>
</body>
</html>
&#13;