简体   繁体   English

为什么jQuery .attr总是说这是未定义的?

[英]Why does jQuery .attr always say that this is undefined?

Here is my code: 这是我的代码:

  $("#packing_list_css").on("click", ".crossable", function() {
    if ($(this).attr("text-decoration") == "none")
      $(this).attr("text-decoration", "line-through");
    if ($(this).attr("text-decoration") == "line-through")
      $(this).attr("text-decoration", "none");
  });

I've been testing different things, and anything that I call .attr() on always is undefined. 我一直在测试不同的东西,而我一直调用.attr()任何东西都是不确定的。 For example, x = $("h1").attr("font-size"); alert(x); 例如, x = $("h1").attr("font-size"); alert(x); x = $("h1").attr("font-size"); alert(x); comes out as undefined. 出现为未定义。

I have .crossable { text-decoration: none; } 我有.crossable { text-decoration: none; } .crossable { text-decoration: none; } set in my CSS. .crossable { text-decoration: none; }在我的CSS中设置。 When I click inspect element, they all say that text-decoration is set to none. 当我单击检查元素时,他们都说文本装饰设置为none。 So I don't know why .attr() always says that it's undefined. 所以我不知道为什么.attr()总是说它是未定义的。

What am I doing wrong, and how can I fix it? 我在做什么错,该如何解决?

.attr() is for HTML attributes, not for CSS properties. .attr()用于HTML属性,不适用于CSS属性。

You're looking for .css() : 您正在寻找.css()

var cssProp = $(this).css('text-decoration'); // Gets the CSS property's value
$(this).css('text-decoration', 'line-through'); // Sets the CSS property's value

Text decoration isn't an attribute it's a CSS value. 文本修饰不是属性,而是CSS值。 Attributes are things like href, class and id on an HTML element. 属性是HTML元素上的href,class和id之类的东西。

Try this: 尝试这个:

$(this).css("text-decoration", "line-through");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM