私はdivのリストを持っています。これは1つのdiv構造です:
<div class="commentWrap" id="@Model.CommentId">
@Model.CommentText
Edit
</div>
divの各編集ボタンのアクションをアタッチしたいdivのIDをdiv
idで区切ります。編集ボタンをクリックすると、これはJQueryの機能です:
$('#editButton').live('click', function (e) {
e.preventDefault();
var container = $(this).closest('div');
var itemId = container.attr('id');
alert(itemId);
})
And it works. It display correct ID of element.
Problem is when I have more than one div. For example when I have 5
div’s and click on some edit button alert message is displayed 5
times???
What I did wrong here?
<div id="messages">
<div style="border-top-width: 1px; border-right-width: 1px; border-bottom-width: 1px; border-left-width: 1px; border-top-style: solid; border-right-style: solid; border-bottom-style: solid; border-left-style: solid; border-top-color: rgb(221, 221, 221); border-right-color: rgb(221, 221, 221); border-bottom-color: rgb(221, 221, 221); border-left-color: rgb(221, 221, 221); ">
Vlada Vucetic 467327
<div class="commentWrap" id="467327">
test 4
Edit
</div>
</div>
<div style="border-top-width: 1px; border-right-width: 1px; border-bottom-width: 1px; border-left-width: 1px; border-top-style: solid; border-right-style: solid; border-bottom-style: solid; border-left-style: solid; border-top-color: rgb(221, 221, 221); border-right-color: rgb(221, 221, 221); border-bottom-color: rgb(221, 221, 221); border-left-color: rgb(221, 221, 221); ">
Vlada Vucetic 980339
<div class="commentWrap" id="980339">
test 3
Edit
</div>
</div>
<div style="border-top-width: 1px; border-right-width: 1px; border-bottom-width: 1px; border-left-width: 1px; border-top-style: solid; border-right-style: solid; border-bottom-style: solid; border-left-style: solid; border-top-color: rgb(221, 221, 221); border-right-color: rgb(221, 221, 221); border-bottom-color: rgb(221, 221, 221); border-left-color: rgb(221, 221, 221); ">
Vlada Vucetic 166111
<div class="commentWrap" id="166111">
test 2
Edit
</div>
</div>
<div style="border-top-width: 1px; border-right-width: 1px; border-bottom-width: 1px; border-left-width: 1px; border-top-style: solid; border-right-style: solid; border-bottom-style: solid; border-left-style: solid; border-top-color: rgb(221, 221, 221); border-right-color: rgb(221, 221, 221); border-bottom-color: rgb(221, 221, 221); border-left-color: rgb(221, 221, 221); ">
Vlada Vucetic 769630
<div class="commentWrap" id="769630">
test 1
Edit
</div>
</div>
</div>
ベストアンサー
IDは一意でなければなりません。 class
には id
を、ドットで#
を置き換えてください。
<div class="commentWrap" id="@Model.CommentId">
@Model.CommentText
Edit
</div>
$('.editButton').live('click', function (e) {
e.preventDefault();
var container = $(this).closest('div');
var itemId = container.attr('id');
alert(itemId);
})