2

以下代码的想法是它有一个 iframe(这是必要的,因为应用程序有这个 html 结构)。当父窗口主体元素具有类“IntelligenceEnabled”时,iframe 会激活所有“a”标记名的警报操作(“我很聪明!”);当类不存在时,iframe 上的链接将自动禁用。

问题是:代码运行良好,但有时当用户在切换(禁用/启用)后单击 iframe 中的“showMessage”链接时,这些链接会重定向到 url(facebook、yahoo、google ......)并且没有显示信息。或相反的效果,消息永远显示。

我做错了什么?(两者都在同一个域 iframe 和父窗口上)

<html>
<script type="tex/javascript" src="/js/jquery-1.9.1.min.js"></script>
<script>
$(document).ready( function() {

    $("body.IntelligenceEnabled #IamIntelligent").on( 'load', function() {
        $("body.IntelligenceEnabled #IamIntelligent").contents().delegate( '.showMessage', 'load', function() {
            alert("I'am intelligent");
            return false;
        });
     });

     $('#enableIntelligence').click( function() {
        $('body').addClass('IntelligenceEnabled');
        return false;
     });

     $('#disableIntelligence').click( function() {
        $('body').removeClass('IntelligenceEnabled');
        return false;
     });

});
</script>
<body>
<iframe id="IamIntelligent" src="/foo.html"></iframe>
<a href="#" id="enableIntelligence">Enable my intelligence!</a>
<a href="#" id="disableIntelligence">Make me gross!!!</a>
</body>
</html>

(/foo.html)

<html>
<body>
<a href="http://www.google.com" class="showMessage">Google</a>
<a href="http://www.facebook.com" class="showMessage">Facebook</a>
<a href="http://www.yahoo.com" class="showMessage">Yahoo</a>
<a href="http://www.microsoft.com" class="showMessage">Microsoft</a>
</body>
</html>
4

1 回答 1

1

U 不能在加载时将事件委托给 iframe 内容,例如

$("body.IntelligenceEnabled #IamIntelligent")

这甚至没有被执行。

使用以下代码获取您的功能。

$("#IamIntelligent").on( 'load', function() {
    $("#IamIntelligent").contents().delegate( '.showMessage', 'click', function(e) {
        if($(document.body).hasClass("IntelligenceEnabled")) {
            alert("I'am intelligent");
            return false;
        }
    });
 });
于 2013-03-26T06:16:34.847 回答