如何用jQuery獲取點選元素最近的輸入值?
如需用jQuery獲取點選元素最近的輸入值,請按照下列步驟操作:
- 你需要用closest找到匹配給定值的最近祖先元素。
- 現在,用屬性等於選擇器,找到具有指定名稱的輸入。
- 最後一步是用val()方法來檢索輸入值。
我們先看看如何新增jQuery:
示例
你可以嘗試執行下列程式碼用jQuery從點選元素中獲取最近的輸入值:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".add").on("click", function () {
var v = $(this).closest("div.content").find("input[name=’rank’]").val();
alert(v);
});
});
</script>
</head>
<body>
<div class="content">
<div class="ranking">
<label>Rank:</label>
<input type="text" name="rank" value="1"/>
</div>
<div class="buttons">
<a href="#" class="add">Click</a>
</div>
</div>
</body>
</html>
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP