利用jQuery选择器和jQuery中的DOM操作实现九宫格拼图

    <script type="text/javascript">
        $(function () {
            $("td").click(function () {

                var str = $(this).attr("id");//获取当前点击<td>的id
               
                if ((parseInt(str) + 3) < 10 && $("#table1 td[id=" + (parseInt(str) + 3) + "]").children().length == 0) {//向下
                    $(this).find("img").appendTo("td[id=" + (parseInt(str) + 3) + "]");
                }
                else if (parseInt(str) % 3 != 0 && $("#table1 td[id=" + (parseInt(str) + 1) + "]").children().length == 0) {//向右
                    $(this).find("img").appendTo("td[id=" + (parseInt(str) + 1) + "]");
                }
                else if ((parseInt(str) - 3) > 0 && $("#table1 td[id=" + (parseInt(str) - 3) + "]").children().length == 0) {//向上
                    $(this).find("img").appendTo("td[id=" + (parseInt(str) - 3) + "]");
                }

                else if (parseInt(str) % 3 != 1 && $("#table1 td[id=" + (parseInt(str)-1) + "]").children().length == 0) {//向左
                    $(this).find("img").appendTo("td[id=" + (parseInt(str) - 1) + "]");
                }

            })

        })
    </script>

<body>

    <div class="box">

        <table id="table1" class="mytable">
            <tr>
                <td id="1">
                    <img src="Files/01.gif" /></td>
                <td id="2">
                    <img src="Files/02.gif" /></td>
                <td id="3">
                    <img src="Files/03.gif" /></td>
            </tr>
            <tr>
                <td id="4">
                    <img src="Files/04.gif" /></td>
                <td id="5">
                    <img src="Files/05.gif" /></td>
                <td id="6">
                    <img src="Files/06.gif" /></td>
            </tr>
            <tr>
                <td id="7">
                    <img src="Files/07.gif" /></td>
                <td id="8">
                    <img src="Files/08.gif" /></td>
                <td id="9"></td>
            </tr>
        </table>

    </div>

</body>

posted @ 2018-08-17 16:03  海客者  阅读(394)  评论(0编辑  收藏  举报