我試圖有一個按鈕,當點擊它時,會有一些 jQuery 代碼鏈接到它。請參閱下面的總體布局。但是,表格上的行數是可變的。所有按鈕都應具有相同的操作,但應用于其父元素。我怎樣才能做到這一點?
謝謝
td {
border: 1px solid black;
padding: 10px;
}
<table>
<tr>
<td>Info</td>
<td><button class="remove">Remove row</button></td>
</tr>
<tr>
<td>Info</td>
<td><button class="remove">Remove row</button></td>
</tr>
<tr>
<td>Info</td>
<td><button class="remove">Remove row</button></td>
</tr>
</table>
uj5u.com熱心網友回復:
您可以通過多種方式做到這一點,問題用 jQuery 標記,因此使用 jQuery 的最簡單方法是:
$("button").on("click", function(ev) {
$(this).parents("tr").remove()
});
這將tr在單擊它的按鈕時洗掉元素,您可以在該匿名函式中執行您想要的操作
uj5u.com熱心網友回復:
試試這個
let btns = $("button.remove"); // you will select only buttons with remove class
在你的情況下,你想要這樣的東西:
btns.each(function(){
let btn = $(this);
btn.on('click',()=>{
// your stuff
})
})
我希望它有用!
uj5u.com熱心網友回復:
下面的示例可以滿足您的需要,它將檢查table元素內的任何單擊以查看它是否與所需的模式匹配(在本例中為buttonwith class .remove),然后再執行代碼。
我添加了一個動態添加的行,以便您對其進行測驗。
如果您沒有動態添加行(即在運行此代碼之前它們都存在),那么您可以簡單地使用:
$("table button.remove").click( function() {
$(this).closest("tr").remove();
});
// Add click event linked to the table
// Will trigger whenever a button with class .remove is clicked within the table
$( "table" ).on( "click", "button.remove", function() {
// Move up DOM tree to nearest 'tr' and remove it
$(this).closest("tr").remove();
});
// Add click event to add row button
$("#add-row").click( function() {
// Add dynamic row for testing
$("table").append('<tr><td>Info</td><td><button >Remove row</button></td></tr>');
});
td {
border: 1px solid black;
padding: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>Info</td>
<td><button class="remove">Remove row</button></td>
</tr>
</table>
<button id="add-row">Add Row</button>
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/469015.html
標籤:javascript html jQuery css
