【问题标题】:Jquery .style is undefinedJquery .style 未定义
【发布时间】:2013-01-01 00:16:54
【问题描述】:

我的页面中有很多表格。一些表具有内联定义的 Width 属性 -

style="width:100%; ..."

我需要得到所有这些表。 我试过了

$('.Forum_Container table').each(function () {
    var $this = $(this);
    if ($this.style != undefined) {
        if ($this.style.width == '100%') {
            ...
        }
    } else {
        ...
    }
});

但是 $this.style 总是未定义的。什么会导致这个问题?

【问题讨论】:

    标签: jquery styles undefined


    【解决方案1】:

    jQuery 有.css() 获取元素样式属性:

    if ($this.css("width") == '100%') {
        ...
    } else {
        ...
    }
    

    如果出于某种原因你想要原始样式,你可以从 DOM 元素本身而不是包装它的 jQuery 对象中获取它:

    if (this.style != undefined) {
        if (this.style.width == '100%') {
            ...
        }
    } else {
        ...
    }
    

    this 将为您提供“原始”元素。

    【讨论】:

      【解决方案2】:

      "style" 不是 jQuery 方法。

      “attr”或“prop”是你所追求的

      【讨论】:

        【解决方案3】:

        您正在检查 jQuery 对象style 属性,而不是 DOM 元素。您需要将 jQuery 对象转换为 DOM 元素,如下所示:

        $('.Forum_Container table').each(function () {
            var $this = $(this),
                this_style = this.style;
            if (this_style != undefined) {
                if (this_style.width == '100%') {
                    ...
                }
            } else {
                ...
            }
        });
        

        或者,如果您使用 jQuery,为什么不使用 .css() 方法?

        【讨论】:

        • 执行$this[0].style 与执行this.style 相同,但没有对jQuery() 函数的毫无意义的调用。
        • 谢谢,这是我的疏忽。我已经更新了答案。
        【解决方案4】:

        当您执行$(this) 时,您正在创建一个包含对该DOM 元素的引用的jQuery 对象。 style 属性是 DOM 元素本身的属性,而不是 jQuery 对象,因此尝试访问它是行不通的(因为它未定义的)。

        要么直接使用this(实际的DOM节点)——即this.style.width——要么使用jQuery提供的函数来访问你需要的信息。

        【讨论】:

          【解决方案5】:

          使用css()函数:

          $this.css('width')
          

          在你的if 声明中:

          $this.hasAttr('style')
          

          【讨论】:

            【解决方案6】:

            $this.prop('style').width 将在不使用原始元素的情况下工作。

            我试图确定在早期的 javascript 中边距是否设置为“自动”,$this.prop('style').margin 将返回包含“自动”一词的原始边距值,而 $this.css('margin') 返回计算值。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2010-12-31
              • 2010-09-25
              • 2021-10-25
              • 2019-04-12
              相关资源
              最近更新 更多