在JQuery中追加CSS Div不起作用

Appending to a CSS Div in JQuery is not working

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

我有一个函数,它可以编写一个城镇的描述。我想在div中显示它。但是,当我尝试这样做时,它会将文本放在div的后面,而不是放在里面。

因此,它显示div和文本,但不显示div中的文本。下面是最相关的行(跳过几个不相关的部分):

#description { height: 50px; background-color: #A7DBD8; }

<div id="description"></div>

function town () { document.write("You are in the town of ",placevals[playerlocation][0],"<br>"); }

$("#description").appendTo(town());

我尝试过使用.html并替换div,但也没有成功。(例如'<div id="blue"'>+town()+'</div>'

我可能只是在装聋作哑,但任何帮助都将不胜感激。

您有一个没有返回值的town函数,然后您将调用它的结果(将是undefined)传递给appendTo(它希望您传递一个选择器或元素)。

如果您的目标是将town生成的文本附加到#description div,则:

function town () {
    // Return the text, and use `+` to concatenate strings
    return "You are in the town of " + placevals[playerlocation][0] + "<br>";
}
// Use `append`
$("#description").append(town());

您还应该将文本作为字符串返回,然后可以使用.html()函数将其注入div元素。

//Assuming these variables are defined.
var placevals = {}
    placevals['newyork'] = 'New York';
    playerlocation = 'newyork'
function town () { 
    return 'You are in the town of ' + placevals[playerlocation] + '.';
}
$("#description").html(town('newyork'));

工作示例:http://jsfiddle.net/ZynU9/4/

document.write正在将文本输出到文档中。您的函数可能应该返回一个值,然后您可以使用.html(),它将正确地解释<br>以及您想要的文本。