0

私のコードは次のとおりです。

<!DOCTYPE html>
<html>
<head>
    <title>Demo</title>
    <meta charset="utf-8"/>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function(){
            $("#table1 tr:gt(0) input[type='checkbox']").bind("click",function(){
                var id=  $(this).attr("id");
                var name=$(this).parent().next("td").text();

                if($(this).is(":checked")){
                    $("#table2").append("<tr id="+id+"><td>"+name+"</td></tr>");
                }
                else{
                    $("#table2 #"+id).remove();//why this not work in IE7?
                    //$("#"+id,$("#table2")).remove();//this work well
                }   
            })
        });
    </script>
</head>
<body>
    One:
    <table id="table1" border="1">
        <tbody>
            <tr><th></th><th>name</th></tr>
            <tr><td><input type="checkbox" id="Checkbox1" /></td><td>jim</td></tr>
            <tr><td><input type="checkbox" id="Checkbox2" /></td><td>tom</td></tr>
        </tbody>
    </table>
    <br/>
    Two:
    <table id="table2" border="1">
        <tbody>
            <tr><th>name</th></tr>
        </tbody>
    </table>
</body>
</html>

このコードは非常に単純です。table1 チェックボックスがオンになっている場合は、td を table2 に追加します。それ以外の場合は、td を table2 から削除しますが$("#table2 #"+id).remove();、ie7 では機能しません$("#"+id,$("#table2")).remove();。うまく機能するように置き換えます。誰が理由を教えてくれますか?

4

1 に答える 1

2

この問題は IE7 に固有のもので、おそらく IE7 がサポートされていないためquerySelectorAll、Sizzle が使用されています。

見た目から、既存の要素と同じ ID を共有する新しい要素を作成しています。ID は一意である必要があるため、重複がある場合に DOM 選択が機能することは期待できません。

// Here you're getting the ID of the element that was clicked
var id=  $(this).attr("id");
var name=$(this).parent().next("td").text();

if($(this).is(":checked")){

     // Here you're creating a new element with the same ID!!!
    $("#table2").append("<tr id="+id+"><td>"+name+"</td></tr>");
}
else{
    $("#table2 #"+id).remove();//why this not work in IE7?
    //$("#"+id,$("#table2")).remove();//this work well
}   

しかし、あなたはこれがうまくいくと言います:

$("#"+id,$("#table2")).remove();

これはおそらく、Sizzle がこれを行っているためです。

var el = document.getElementById('table2');

そして、次のようなもの:

el.getElementsByTagName('*')

ID のフィルターが続きます。これは推測にすぎませんが、重複する ID を最初に解決する必要があるため、関係はありません。

于 2012-05-10T02:49:31.207 に答える