【问题标题】:jQuery find style attr of IDjQuery查找ID的样式属性
【发布时间】:2014-12-12 11:46:12
【问题描述】:

如何找到特定 ID 元素的样式属性?

例如

desc = "#thisID";
desc_style = desc.attr('style');
console.log(desc_style);

编辑澄清,上面是一个例子。

Desc 变量保存字符串#thisID。

如何找到该 ID 的样式属性?

【问题讨论】:

  • desc = $("#thisID");不要忘记将 jquery 包含到您的 html 头标签中
  • "#thisID" 是字符串而不是 jquery 对象。
  • 好的,这只是一个例子。 desc 是一个字符串。如何找到该 ID 的属性?
  • $("#thisID").attr("style")

标签: jquery attr


【解决方案1】:

正如我在评论中提到的 desc 是一个字符串而不是一个 jquery 对象,所以你不能使用 jquery 方法。您可以简单地使用:

$("#thisID").attr("style");

【讨论】:

    【解决方案2】:

    使用此语法返回一个 jQuery 对象

    desc = $("#thisID");
    

    然后你就可以得到你正在做的样式

    desc_style = desc.attr('style');
    console.log(desc_style);
    

    编辑:

    如果您想将desc 保留为字符串,请执行以下操作:

    desc = "#thisID"
    desc_style = $(desc).attr('style');
    console.log(desc_style);
    

    【讨论】:

    • 我已经在 OP 中澄清了。代码就是一个例子。 #thisID 正确存储在字符串中。如何找到该 ID 的样式属性内容?
    【解决方案3】:

    如果desc持有字符串#thisID,那么

    desc_style = $(desc).attr('style');
    console.log(desc_style);
    

    或者,如果desc只持有thisID,那么你需要在它之前连接#

    desc_style = $("#" + desc).attr('style');
    console.log(desc_style);
    

    【讨论】:

      【解决方案4】:

      你可以使用类似的东西:

      ("'"+desc+"'").css("styleToGet","settingItIsOptional");
      

      如果 desc 是 #MyElementsID 的字符串值

      如果您只想完全删除 desc,可以使用:

      ("#MyDivID").css("styleToGet","settingItIsOptional");
      

      我相信在这里获得attr("style") 可能是更好的选择,也可能不是更好的选择,但这取决于您的要求。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-08-30
        • 2013-11-03
        • 1970-01-01
        • 2011-05-13
        • 2013-11-04
        • 2021-01-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多