【问题标题】:jQuery error when using $window.load使用 $window.load 时出现 jQuery 错误
【发布时间】:2015-05-08 16:55:48
【问题描述】:

我有以下代码在文档就绪事件中工作:

jQuery(document).ready(function($) {

    $('tr[data-name="background_colour"] input.wp-color-picker').each(function() {

        //this works
        $(this).closest('tr').siblings('tr[data-type="wysiwyg"]').css('background-color', this.value);

        //this doesn't because frames are not loaded
        $(this).closest('tr').siblings('tr[data-type="wysiwyg"]').find('iframe').contents().find('body').css('background-color', this.value);
    });
});

tr 的背景颜色已成功更改,但iframebody 未成功更改,因为所有 iframe 都是动态创建的,并且在文档准备好时它们尚未完全加载。

所以我尝试使用 window.load 代替如下:

jQuery(window).load(function($) {

    $('tr[data-name="background_colour"] input.wp-color-picker').each(function() {

        //this works
        $(this).closest('tr').siblings('tr[data-type="wysiwyg"]').css('background-color', this.value);

        //this doesn't because frames are not loaded
        $(this).closest('tr').siblings('tr[data-type="wysiwyg"]').find('iframe').contents().find('body').css('background-color', this.value);
    });
});

但是当我这样做时,我在下面的行中得到了Uncaught TypeError: object is not a function

$('tr[data-name="background_colour"] input.wp-color-picker').each(function() {

感谢 Guffa 的回答,让这个工作得以实现。以下是可能对其他人有帮助的正确代码:

jQuery(window).load(function() {

    jQuery(function($){

        $('tr[data-name="background_colour"] input.wp-color-picker').each(function() {
            $(this).closest('tr').siblings('tr[data-type="wysiwyg"]').css('background-color', this.value);

            $(this).closest('tr').siblings('tr[data-type="wysiwyg"]').find('iframe').contents().find('body').css('background-color', this.value);
        });
    });
});

【问题讨论】:

  • 你能告诉我们你的html代码或你正在使用的属性的父表吗
  • 生成 iframe 的代码是什么?我建议将此代码移至该位置。
  • 代码是从 wordpress 插件生成的。非常简化版本的 html 代码类似于 jsfiddle.net/LcssrmL8

标签: javascript jquery html css iframe


【解决方案1】:

ready 事件处理程序以 jQuery 对象作为参数调用,但 load 事件处理程序不是。

由于您将$ 作为load 事件处理程序的参数,因此它将包含事件对象,而不是jQuery 对象。当你尝试将事件对象当作 jQuery 对象来使用时,你会得到一个错误。

load 事件处理程序中移除参数,以便您可以从全局范围访问$ 变量:

jQuery(window).load(function() {

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-26
    相关资源
    最近更新 更多