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

时间:2014-03-24 01:28:14

标签: javascript jquery css

这是我的代码:

  $("#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");
  });

我一直在测试不同的东西,而且我称之为.attr()的任何东西都是未定义的。例如,x = $("h1").attr("font-size"); alert(x);以未定义的形式出现。

我在CSS中设置了.crossable { text-decoration: none; }。当我点击inspect元素时,他们都说text-decoration设置为none。所以我不知道为什么.attr()总是说它未定义。

我做错了什么,我该如何解决?

2 个答案:

答案 0 :(得分:3)

.attr()用于HTML属性,不适用于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

答案 1 :(得分:1)

文本修饰不是属性,而是CSS值。属性类似于HTML元素上的href,class和id。

试试这个:

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