【问题标题】:Manipulating data of dynamic html tags jQuery [duplicate]处理动态html标签jQuery的数据[重复]
【发布时间】:2017-02-20 18:40:59
【问题描述】:

我有这个代码,

    $('#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"

谢谢。

【问题讨论】:

    标签: jquery html class src attr


    【解决方案1】:

    您的代码未将事件侦听器绑定到动态创建的 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>

    【讨论】:

    • 谢谢,它正在工作,但 iframe 无法导航到所需的网络,为什么?
    • 这是因为您选择的网页 (google/microsoft) 阻止在其他网页的 iframe 中显示它们。尝试使用不同的 URL,例如 Wikipedia.org。我更新了一个例子。
    • 谢谢,完整回复+1
    猜你喜欢
    • 1970-01-01
    • 2017-10-02
    • 1970-01-01
    • 1970-01-01
    • 2019-11-30
    • 2020-10-20
    • 1970-01-01
    • 1970-01-01
    • 2016-03-27
    相关资源
    最近更新 更多