Jquery 样式未定义

Jquery 样式未定义,jquery,styles,undefined,Jquery,Styles,Undefined,我的页面中有很多表格。某些表具有内联定义的宽度属性- style="width:100%; ..." 我需要弄到所有这样的桌子。 我试过了 但是$this.style始终是未定义的。什么会导致此问题?jQuery使用.css()获取元素样式属性: if ($this.css("width") == '100%') { ... } else { ... } 如果出于某种原因需要原始样式,可以从DOM元素本身而不是包装它的jQuery对象获取它: if (this.style !

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

style="width:100%; ..."
我需要弄到所有这样的桌子。 我试过了

但是$this.style始终是未定义的。什么会导致此问题?

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

if ($this.css("width") == '100%') {
    ...
} else {
    ...
}
如果出于某种原因需要原始样式,可以从DOM元素本身而不是包装它的jQuery对象获取它:

if (this.style != undefined) {
    if (this.style.width == '100%') {
        ...
    }
} else {
    ...
}
this
将为您提供“原始”元素。

“样式”不是jQuery方法


“attr”或“prop”是您在检查jQuery对象的
样式
属性,而不是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,为什么不使用该方法呢?

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

直接使用
this
(实际的DOM节点)-即
this.style.width
-或使用jQuery提供的函数访问所需信息。

使用
css()
函数:

$this.css('width')
在您的
if
语句中:

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


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

执行
$this[0]。style
与执行
this.style
相同,但是没有对
jQuery()
函数的无意义调用。谢谢你,这是我的疏忽。我已经更新了答案。
$this.hasAttr('style')