「jQuery」clickメソッドでクリック行の値を取得する

環境
jQuery 3.6.0

書式
クリックされた箇所($(this))から値(text())を取得します。
const 変数名 = $(this).text();
$(セレクタID名).text(変数名);

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<div>クリック行の値: <span id="cft"></span></div>
<table>
<tr><td class="city">1001</td><td>東京</td></tr>
<tr><td class="city">2002</td><td>大阪</td></tr>
<tr><td class="city">3003</td><td>福岡</td></tr>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(".city").click(function () {
const val = $(this).text();
$("#cft").text(val);
});
</script>
<div>クリック行の値: <span id="cft"></span></div> <table> <tr><td class="city">1001</td><td>東京</td></tr> <tr><td class="city">2002</td><td>大阪</td></tr> <tr><td class="city">3003</td><td>福岡</td></tr> </table> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> $(".city").click(function () { const val = $(this).text(); $("#cft").text(val); }); </script>
<div>クリック行の値: <span id="cft"></span></div>
<table>
  <tr><td class="city">1001</td><td>東京</td></tr>
  <tr><td class="city">2002</td><td>大阪</td></tr>
  <tr><td class="city">3003</td><td>福岡</td></tr>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
  $(".city").click(function () {
    const val = $(this).text();
    $("#cft").text(val);
  });
</script>

結果
「2002」行を押下すと、「クリック行の値」に「2002」が表示されます。

jQuery

Posted by arkgame