,以方便您的生活,編寫JavaScript時使用jQuery。
在這一點
,讓我們假設你的ListItem
控制輸出ul
列表與id
...確保你有一個類,讓我們想象一下,你被點名了list-item
所以在最後,你將有:
<div id="ListItem_1" class="list-item">
...
</div>
現在,你說你某種該列表內的按鈕...
<div id="ListItem_1" class="list-item>
<input id="ListItem_1_Button_1" type="button" value="I'm a Button" />
</div>
再一次明確給出該按鈕一類的名稱,例如:inside-button
我不知道你是如何有所有文字,但我會再次假設,這將是一個hiiden
場提醒文字...
一些事情,如:
<div id="ListItem_1" class="list-item>
<input id="ListItem_1_Button_1" type="button" value="I'm a Button" />
<input id="ListItem_1_Hidden_1" type="hidden" class="text" value="Text to run" />
</div>
假設你有10只列出幾個按鈕,你可以簡單的寫:
$(".inside-button").bind("click", function() {
// a button was clicked, let's do something
});
是第一行說:「有在inside-button
類名的foreach DOM元素TACH click事件」
和裏面你火你想要做
從你的問題是什麼,你只希望該列表上執行的東西:
$(this) // that will be the .inside-button element, so the Button
.closest(".list-item") // get me the closest DOM element with a class name of "list-item"
.find(".text") // find the DOM elemnt with the class name "text"
.val(); // let's see what value that element has
那麼你可以alert()
它。
一起:
$(".inside-button").bind("click", function() {
// a button was clicked, let's do something
var txt = $(this).closest(".list-item").find("text").val();
alert(txt);
});