2017-02-20 35 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