0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

htmxを使ってみた-(4)htmxを使う-

Last updated at Posted at 2024-10-22

htmxを使う

練習プログラムでは、一覧表の1行を次のように出力しています。

<tr id="inst_26" hx-on::before-swap="change_institution(event)">
	<td class="pseude_link" hx-get="/view_institution/26" hx-target="#detail" hx-on::after-request="show_dialog()">あかんだな駐車場</td>
	<td>高山市奥飛騨温泉郷平湯791番地38</td>
	<td>有料駐車場、バス待合所</td>
	<td></td>
	<td></td>
	<td class="pseude_link" hx-get="/edit_institution/26" hx-target="#detail" hx-on::after-request="show_dialog()">*</td>
	<td class="pseude_link" hx-delete="/del_institution/26/5" hx-target="#inst_26" hx-swap="delete" hx-confirm="データを削除します。削除したデータを戻すことはできません。">x</td>
</tr>

上記の2行目

<td class="pseude_link" hx-get="/view_institution/26" hx-target="#detail" hx-on::after-request="show_dialog()">あかんだな駐車場</td>

の意味は、

  1. <td>要素がクリックされたら、
  2. hx-get属性により、HTTPのGETメソッドで/view_institution/26にアクセスし、
  3. hx-target属性により、サーバーからの応答で idに"detail"を持つ要素(の中身を書き換え、
  4. hx-on属性により、AJAX終了後(after-request)に、JavaScriptのshow_dialog()関数を呼び出します。

show_dialog()関数はp00.jsにあります。
ht-get などと一緒によく使われると思われる属性には次のようなものがあります。

htmx属性 内容
hx-target サーバーからの応答を書き換える要素を指定。
デフォルトは自分自身
ターゲットはCSSセレクタの形式で指定
hx-swap 要素を書き換える方法。
デフォルトは中身を書き換える。
9種類用意されている
hx-on イベントを設定する。
要素が書き換えられたらなど多くのイベントを設定することができる

hx-onで指定するイベント名について
htmxのホームページには、イベントの名前をキャメルケース(afterRequestなど)で書いてありますが、指定するときにはケバブケース(after-requestなど)にしないといけないようです。

関連記事一覧

htmxを使ってみた-(1)htmxの基本-
htmxを使ってみた-(2)準備-
htmxを使ってみた-(3)ルート関数-
htmxを使ってみた-(4)htmxを使う-
htmxを使ってみた-(5)HTMLのdialog-
htmxを使ってみた-(6)データの表示-
htmxを使ってみた-(7)データ追加-
htmxを使ってみた-(8)要素の変更-
htmxを使ってみた-(9)ページの再読み込み-
htmxを使ってみた-(10)データの変更-
htmxを使ってみた-(11)データベースの排他制御-
htmxを使ってみた-(12)確認ダイアローグ-
htmxを使ってみた-(13)データ削除-(最終)

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?