jQuery removeProp无效

时间:2018-04-04 12:22:09

标签: javascript jquery html

我尝试删除所有样式属性。当我通过.css({cursor:"not-allowed"})添加样式时,元素将如下所示:

<div id="id" style="cursor:not-allowed;">
  My Text
</div>

我知道我可以设置.css({"cursor"=""}),但我不想将每个样式属性设置为""。我不明白.removeProp("style")无效的原因。它不应该这样做吗?

&#13;
&#13;
function applyStyle() {
  $("#id").css({ cursor: "not-allowed" });
}

function removeStyle() {
  $("#id").removeProp("style");
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="id">
  My Text
</div>
<button onclick="applyStyle()">Apply style</button>
<button onclick="removeStyle()">Remove style</button>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:3)

使用removeAttr,因为style是属性

&#13;
&#13;
function applyStyle() {
  $("#id").css({ cursor: "not-allowed" });
}

function removeStyle() {
  $("#id").removeAttr("style");
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="id">
  My Text
</div>
<button onclick="applyStyle()">Apply style</button>
<button onclick="removeStyle()">Remove style</button>
&#13;
&#13;
&#13;