2017-02-20 33 views
0

我有這樣的代碼,操縱動態HTML標籤的數據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標籤的事件處理程序?

我不想使用target =「result」

謝謝。

回答

2

您的代碼沒有將事件偵聽器綁定到dinamicly創建的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

這是因爲您選擇的網頁(谷歌/微軟)將其顯示在其他網頁的iframe中。嘗試使用不同的網址,例如Wikipedia.org。我更新了一個例子。 –

+0

謝謝,完整回覆+1 – eawedat