开发者

Why doesn't JQuery's removeAttr always work?

When trying to see why removeAttr doesn't always seem to work I tried.

$("div#mydiv").css('height','200px');  
$("table").removeAttr("border");  
$("#mydiv").removeAttr("height");  

The table borders attribute is removed OK but not the div height attribute. I need to use other suggested methods such as

$("#mydiv").css('hei开发者_如何学编程ght','auto')  

to alter it but not actually remove it.

I would be interested to know what makes removeAttr not work in this scenario? There is no other css anywhere.


removeAttr refers to the attributes of the tag. So, given:

<span title="my-title" id="my-id" style="height: 4px; padding: 200px;" />

That span has three attributes, title, id, and style. removeAttr will let you remove any of these. But here's the trick, while removeAttr will let you remove the style attribute, it can only remove both height and padding, it cannot edit either.

This:

$("#my-id").removeAttr("style");

results in:

<!-- not literally, but this is the best way to explain it -->
<span title="my-title" id="my-id" />

css, on the other hand, lets you edit that style attribute directly.

This:

$("#my-id").css("height", "2px");

results in:

<span title="my-title" id="my-id" style="height: 2px; padding: 200px;" />

Now, to remove just the height, you can pass an empty string to the second parameter.

This:

$("#my-id").css("height", "");

results in:

<span title="my-title" id="my-id" style="padding: 200px;" />


The height is an inline css styling which means it's inside the style attribute. I think you can do this instead

$('#mydiv').css('height', '');


This is supposed to work on attributes like id, href, disabled, selected, etc... Even css that's used inline is part of the "style" attribute. You could remove the style attribute but not pieces inside of it.

You may try $("#mydiv").css('height', '');

I don't recall what happens when you pass an empty string the the css function.


Use jQuery's height:

$(document).ready(function() {
    $("div#mydiv").css('height', '200px');

    $('#clicker').click(function() {
        $('#mydiv').height('')
    });
});

Example jsFiddle

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜