开发者

Bug in Safari: options.length = 0; not working as expected in Safari 4

This is not a real question, but rather an answer to save some others the hassle of tracking this nasty bug down. I wasted hours finding this out.

When using options.length = 0; to reset all options of a select element in safari, you can 开发者_JS百科get mixed results depending on wether you have the Web Inspector open or not. If the web inspector is open you use myElement.options.length = 0; and after that query the options.length(), you might get back 1 instead of 0 (expected) but only if the Web Inspector is open (which is often the case when debugging problem like this).

Workaround:

Close the Web Inspector or call myElement.options.length = 0; twice like so:

myElement.options.length = 0;
myElement.options.length = 0;

Testcase:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
        "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
 <title>Testcase</title>
<script type="text/javascript" language="javascript" charset="utf-8">
function test(el){
 var el = document.getElementById("sel");
 alert("Before calling options.length=" + el.options.length);
 el.options.length = 0;
 alert("After calling options.length=" + el.options.length);
}
</script>
</head>
<body onLoad="test();">
<p>
Make note of the numbers displayed in the Alert Dialog, then open Web inspector, reload this page and compare the numbers.
</p>

<select id="sel" multiple>
 <option label="a----------" value="a"></option>
 <option label="b----------" value="b"></option>
 <option label="c----------" value="c"></option>
</select>
</body>

</html>


Close the Web Inspector or call myElement.options.length = 0; twice like so:

myElement.options.length = 0;
myElement.options.length = 0;


Can't reproduce that with current dev-channel version. 5.0.375.6


Try:

myElement.options.splice(0, myElement.options.length);

(first param is the starting index, second param indicates how many elements to delete)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜