本稿では返信機能を実装します。
返信ボタンを押してモーダルウィンドウを表示し、 ウィンドウのテキストフィールドに返信相手のIDが挿入されたら完成です。
- 返信ボタンを押してモーダルウィンドウが出ることの確認
- jQueryを使った返信先のIDの挿入
まずは投稿一覧(index.php
)を表示して返信する
ボタンを押しましょう。
投稿用のモーダルウィンドウは表示されましたか?
表示されない場合は
トップページの作成
に戻ってindex.php
のHTML部分を再確認しましょう。
モーダルウィンドウが表示された方はindex.phpで 下記のソース部分を確認しましょう。 以下のソースは既に記述したモーダルウィンドウの表示部分と、返信ボタンの部分です。
...
...
<!-- replyModal -->
<div class="modal fade" id="replyModal" tabindex="-1" role="dialog" aria-labelledby="replyModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="replyModalLabel">リプライ</h4>
</div>
<div class="modal-body">
<form action="index.php" method="post">
<div class="form-group">
<label for="replyText" class="control-label">メッセージ(140字まで):</label>
<textarea class="form-control" id="replyText" name="postText" maxlength="140"></textarea>
</div>
<button type="submit" class="btn btn-primary">返信する</button>
</form>
</div>
</div>
</div>
</div>
...
...
...
...
<button type="button" class="btn btn-primary reply-btn" data-toggle="modal" data-target="#replyModal">
<span class="glyphicon glyphicon-send" aria-hidden="true"></span> 返信する
</button>
...
...
では本題です。 jQueryを使って返信先のIDを取得して、 モーダルウィンドウに挿入します。
jQueryとはJavaScriptのライブラリの1つで、JavaScriptの記述を容易に行えるようになります。 jQueryを使ったことがない人は jQuery入門 やjQuery公式ドキュメント を参照してみてください。
まずはindex.php
の</body>
の前に下記のコードを写しましょう。
...
...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<!-- 追記ここから -->
<script type="text/javascript">
$(function () {
// リプライ時にスクリーンネームを埋めておく
$('.reply-btn').click(function () {
var $screen_name = $(this).parent().siblings('.reply-to').text();
$('#replyText').val($screen_name + ' ');
});
});
</script>
<!-- 追記ここまで -->
</body>
...
...
まず、$('.reply-btn').click(function () {...}
と書くことによって、classにreply-btn
を指定している要素がクリックされたときを検知できるようにしています。
次にクリックされたときの処理を記述します。
index.php
の中から下記のreply-btn
の部分を探しましょう。
...screen_name...
...... ...
...取得したい返信先のID(screen_name)は<p class="small text-muted reply-to">...</p>
の要素の中にありますね。
このp
要素は先ほど取得したbutton
の親要素のp
の兄弟要素の位置にあります。
ここから取得することを目指します。
$(this).parent().siblings('.reply-to').text();
のthis
はreply-btn
で取得したbutton
を意味しています。
図解すると赤丸の位置を指しています。
次にparent()
によってその親要素を取得しています。
parent()
で取得される親要素はなんでしょうか?
<p class="text-right">
ですね。
下図のbutton
要素の赤矢印で示されている要素になります。
続いて.siblings('.reply-to')
で兄弟要素の中からreply-to
クラスを指定して取得しています。
これで目的の<p class="small text-muted reply-to">...</p>
の要素を取得できました。
最終的な図は以下のようになります。
無事に目的の
p
要素を取得できていますね。
そして.text()
では要素の中身を取得しています。
最後に$('#replyText').val($screen_name + ' ');
ですが、
モーダルウィンドウのテキストを#replyText
で指定して、screen_name
を挿入しています。
無事に返信機能の実装はできましたか? jQueryとHTMLのやり取りに慣れていない方には難しいところもあったかもしれません。 その方は参考URLを読んでjQueryに慣れてみることをオススメします!