2017-02-20 18 views
0

私はこのコードを持って、操作データjQueryの

$('#gogo').click(function(e){ 

    var data='<a href="http://www.google.com" class="myButtons">Google</a><a href="http://www.microsoft.com" class="myButtons">Microsoft</a>"; 
      $("#showResults").html(data); 

    }); 


    $(".myButtons").click(function(e) { 
     e.preventDefault(); 
     alert($(this).attr("href")); 
     $("#result").attr("src", $(this).attr("href")); 
    }); 


<button id="gogo">Click me</button> 

<div id="showResults"></div> 

<iframe id="result" name="result" src="" width="750px" height="450px" frameBorder="0"></iframe> 

それが機能しない理由、私が思っていました。新しい追加されたhtmlタグのイベントハンドラがないのでおそらくそれはありますか?

私は

ありがとうターゲット=「結果」を使用する必要はありません。

答えて

2

あなたのコードは、ダイナミックに作成されたdomノードにイベントリスナーをバインドしていません。私の解決策を確認してください:なぜ、

$('#gogo').click(function(e){ 
 
    var data='<a href="http://wikipedia.org" class="myButtons">Wikipedia</a><a href="http://www.microsoft.com" class="myButtons">Microsoft</a>'; 
 
    $("#showResults").html(data); 
 
}); 
 

 

 
$("body").on("click", ".myButtons", function(e) { 
 
    e.preventDefault(); 
 
    alert($(this).attr("href")); 
 
    $("#result").attr("src", $(this).attr("href")); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<button id="gogo">Click me</button> 
 

 
<div id="showResults"></div> 
 

 
<iframe id="result" name="result" src="" width="750px" height="450px" frameBorder="0"></iframe>

+0

は、それが働いている、あなたに感謝しますが、IFRAMEは所望のウェブに移動しないのですか? – eawedat

+0

これは、あなたが選択したウェブページ(google/microsoft)が他のウェブページのiframeにそれらを表示しないためです。 Wikipedia.orgのような別のURLを試してみてください。私は例を更新しました。 –

+0

ありがとう、完全な応答+1 – eawedat