自作関数を作成して、「指定した要素内のpタグをクリックしたら、pタグのテキストがアラートで表示される」というものを作成しました。
$('#test1').pAlert();
$('#test2').pAlert();
設定はこのようにして行い、ここまでは無事動くのですが、
クリック以外でもアラートを出せるような関数が欲しく、プラグイン内にselectAlertという関数を用意しましたが、思った通りの動きが出来ません。
HTML全体をまずは見て頂きたいです。
HTML
1<!DOCTYPE html> 2<html lang="jp"> 3<head> 4<meta charset="utf-8"> 5<title>JQUERY TEST</title> 6<style> 7#test1, #test2{ 8 padding: 10px; 9 color: #FFF; 10} 11 12#test1{ 13 background-color: red; 14} 15 16#test2{ 17 margin-top: 10px; 18 background-color: blue; 19} 20 21p{ 22 cursor: pointer; 23} 24</style> 25</head> 26<body> 27<div id="test1"> 28 <p class="p1">おはようございます</p> 29 <p class="p2">Hello</p> 30</div> 31<div id="test2"> 32 <p class="p1">おやすみなさい</p> 33 <p class="p2">Good Night</p> 34</div> 35<input type="button" class="method" value="関数実行"> 36 37<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> 38<script type="text/javascript"> 39$(function(){ 40 41 $('#test1').pAlert(); 42 $('#test2').pAlert(); 43 44 //#test1内の.p1内テキストのアラートを出したいが、#test2のp1が実行される 45 $('.method').click(function(){ 46 $('#test1').pAlert.selectAlert('.p1'); 47 }); 48 49}); 50</script> 51<script type="text/javascript"> 52(function($){ 53 54 $.fn.pAlert = function(){ 55 56 var parent = $(this); 57 58 parent.find('p').click(function(e){ 59 alert($(this).text()); 60 }); 61 62 $.fn.pAlert.selectAlert = function(selecter){ 63 alert(parent.find(selecter).text()); 64 }; 65 } 66 67})(jQuery); 68</script> 69</body> 70</html>
$('#test1').pAlert.selectAlert('.p1');
は、クリック以外でも指定した要素(ここでは#test1)の子要素の指定のタグ(ここでは.p1)のアラートを出したいのですが、表示されるのは#test2内のp1のアラート「おやすみなさい」です。
おそらくは、
$('#test1').pAlert();
$('#test2').pAlert();
の設定の際に、parentの値が上書きされてしまったから起こっていることだと思うのですが、要素毎のカスタムメソッド内の変数は共有されてしまうのでしょうか。
また、関数のほうで、指定した$('#test1')を親要素として中の子要素内から探すには、どのような設定が好ましいでしょうか?
お詳しい方、ご教示お願い致します。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/11/21 03:12