开发者

jQuery selector returns duplicate elements in Safari

开发者 https://www.devze.com 2022-12-21 11:18 出处:网络
I have a jQuery selector that queries elements by tag name and class.In a query that I\'d expect to return three elements, Safari (v3.1.1 for Windows) returns an extra element.

I have a jQuery selector that queries elements by tag name and class. In a query that I'd expect to return three elements, Safari (v3.1.1 for Windows) returns an extra element.

The cause seems to be the numeric ID*. Changing the ID to a non-numeric eliminates the duplicate element. Strangely, changing the ID of the first element to other numbers has a seemingly-random effect on the final result count. An ID of 4 increases the result count to five. 0, 9, and 1234 all return four elements.

&开发者_运维百科lt;div class="mydiv" id="1"></div>
<div class="mydiv" id="2"></div>
<div class="mydiv" id="3"></div>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.1.min.js"></script>
<script type="text/javascript">
    $(function()
    {
        var div = $('div.mydiv');
        alert( div.length );                // Safari 3.1.1 returns 4
        alert( $.unique( div ).length );    // Safari 3.1.1 returns 3
    } );
</script>

Firefox 3 and IE 7 display 3 in both alert boxes.

* I know that numeric IDs are not valid HTML identifiers. The jqGrid plugin I'm using uses numbers for row IDs by default. I'll look into changing this behavior, but in the meantime I'm curious why this is affecting the above query.

EDIT

It's been a while since I looked at my data retrieval code for jqGrid. It turns out that I can set row IDs to be whatever I want on the server.


Short answer: You will always get unpredictable behavior when using invalid HTML. (Even if what you're doing works 95% of the time)

The issue is just as you stated, numerical IDs aren't valid, so when doing counts, etc, the browser is free to make this assumption...if they are invalid and it causes a bug, well...it's not their bug.

0

精彩评论

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

关注公众号