【问题标题】:jquery, cannot add img in tdjquery,无法在 td 中添加 img
【发布时间】:2014-04-06 17:18:19
【问题描述】:

我的 html 设置是我在 td 中有字母 imgs。用户应按字母顺序单击图像,每次正确单击图像都会被删除。如果错误,会出现一个xmark。

(代码中还没有:错了三下,游戏结束,然后我会问用户是想再玩还是回家)

这是我的 jquery 代码:

  var error = 0;
        var check = 0;
        $("table img").bind('click',function(){    
            var letterArray = new Array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
            var clickedValue = $(this).attr('name');


            if(clickedValue ==letterArray[check]){
                $(this).parent().empty(); 
                check+=1;
            } else {
                error+=1;
                $("error").add('<td><img src="images/xmark.png" alt="xmark" name="xmark"/></td>');
                if(error==3){
                    alert("Game Over. Homer will now eat you!");
                    $("table img").unbind("click");
                    $("table img").css("opacity", "0.4");
                }
            }
        }); 

我的 html 表格:为简洁起见,只发布了前 6 个字母。

       <table>
            <tr class="rows">
                <td><img src="images/Z.png" alt="Z" name="Z"/></td>
                <td><img src="images/R.png" alt="R" name="R"/></td>
                <td><img src="images/S.png" alt="S" name="S"/></td>
                <td><img src="images/U.png" alt="U" name="U"/></td>
                <td><img src="images/B.png" alt="B" name="B"/></td>
                <td><img src="images/A.png" alt="A" name="A"/></td>
            </tr>
       </table> 
       <table><tr id="error"></tr></table>

【问题讨论】:

  • 这里有问题吗?

标签: jquery image add html-table


【解决方案1】:

使用.appendTo() 代替.add()

试试这个:

var error = 0;
        var check = 0;
        $("table img").bind('click',function(){    
            var letterArray = new Array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
            var clickedValue = $(this).attr('name');
            if(clickedValue ==letterArray[check]){
                $(this).parent().empty(); 
                check+=1;
            } else {
                error+=1;
                $('<td><img src="images/xmark.png" alt="xmark" name="xmark"/></td>').appendTo("tr#error");
                if(error==3){
                    alert("Game Over. Homer will now eat you!");
                    $("table img").unbind("click");
                    $("table img").css("opacity", "0.4");
                }
            }
        }); 

DEMO

【讨论】:

    猜你喜欢
    • 2012-05-02
    • 2012-02-20
    • 2015-12-16
    • 2012-09-30
    • 2011-09-08
    • 2017-08-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多