jquery追加不起作用

jquery append not working

本文关键字:不起作用 追加 jquery      更新时间:2023-09-26

我四处搜索,但找不到答案。我正在制作一个小纸牌游戏,如果创建了某张卡牌,我需要游戏附加一些文本。附加文本适用于点击事件,但不适用于此函数。该函数会正确触发,因为控制台会记录和此类触发。我真的不确定我做错了什么?

function ghostcheck() {
    if (hand[0][0] == 'ghost'){
    ghostpresent = true;
    console.log("It's a ghost!!");
    $("#infocard").append("<p>Oh no! A ghost! What would you like to do?<br><br></p>");
}

感谢您对此事的任何帮助!

我有一个想法,您尝试附加某些文本的元素是动态创建的。

你可以使用 jQuery 的 live() 事件来处理这样的问题。

链接在这里

希望这有帮助..

function ghostcheck() {
    if (hand[0][0] == 'ghost'){
        ghostpresent = true;
        console.log("It's a ghost!!");
        console.log("Is there InfoCard? ", $("#infocard").length > 0);
        $("#infocard").append("<p>Oh no! A ghost! What would you like to do?<br><br></p>");
    }
}

如果你能看到"这是一个鬼!!"和"有信息卡吗?真"在控制台上,这意味着附加文本是有效的。

我认为另一个事件处理程序是在鬼影检查函数附加见文本后重置信息卡元素。

只是为了确保仔细检查"#inforcard"在您的 html 中是否正确拼写。

我的建议是尝试:

//declare this at the start
$infoCard = $('#infoCard');
function ghostcheck() {
  $infoCard.append('<p>Oh no! A ghost! What would you like to do?<br><br></p>');
}
ghostcheck();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="infoCard">
  ghost
</div>

看看这是否有效

尝试这样的事情。有时 - 我不知道为什么 - 你必须将元素分配给一个变量,并确保你在所有地方都使用此变量作为参考。

var infoCard = $("#infocard");
function ghostcheck() {
    if (hand[0][0] == 'ghost'){
    ghostpresent = true;
    console.log("It's a ghost!!");
    infoCard.append("<p>Oh no! A ghost! What would you like to do?<br><br></p>");
   }
}