事件未在iframe内执行

时间:2012-06-05 06:00:39

标签: javascript jquery

我正在iframe dynamically中添加内容,并且该内容与使用.live() function的事件捆绑在一起:

           <body>
            <div id="container">
               <iframe id="if" src="something"></iframe>
            </div>

            <script>
             /* binding event */
             $(document).ready(function() {
               $("p").live("mouseover", function() { /* do something */ });
             });

             /* appending content */
              $("#if").contents().find("#someid").append("<p></p>");                  
            </script>
           </body>

p tag已成功添加,但该事件未在鼠标悬停时执行。有什么问题?

注意:我无法在iframe中添加绑定事件脚本。

1 个答案:

答案 0 :(得分:1)

您的实时绑定仅适用于不适用于iframe的主文档。你有没有尝试过?

使用jQuery 1.4及更高版本使用jQuery delegate

$("#if").ready(function() {
    $("#if").contents().delegate("p", "mouseover", function() {
        // do something
    });
});

使用jQuery 1.7及更高版本使用jQuery on

$("#if").ready(function() {
    $("#if").contents().on("mouseover", "p", function() {
        // do something
    });
});

另请参阅example for delegate()example for on():在“mouseevent loaded”警报后悬停云图。

P.s。:这将定位iframe中的所有<p>。但iframe只会在不违反浏览器的跨网站政策的情况下进行解析。