无法使用jQuery将HTML代码附加到一个div中 [英] Can't append HTML code into one div by using jQuery

查看:135
本文介绍了无法使用jQuery将HTML代码附加到一个div中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个div id = userinfo

I have one div id=userinfo

<html>
<head></head>
<body>
<div id=userinfo></div>
</body>
</html>

现在,我想在此div中添加一些内容,具体取决于localStorage.

And now I want to append something into this div, depending on the localStorage.

if (localStorage==0){$("#userinfo").append("<p>Test</p>");} else {$("#userinfo").append("<p>Hello</p>");}

但是失败了,无论我将此脚本输入到单独的JS文件中还是将其添加到html文件的开头. 我尝试使用Google chrome开发人员工具的控制台排除此错误,它按预期工作.

But it failed, no matter I input this script into separate JS file or add them into the head of the html file. I tried exclude this with Google chrome developer tool's console, it works as expected.

我尝试了另一种方法来将脚本更改为:

I've tried another way round change the script into:

if (localStorage==0){alert("Test");} else {alert("Hello");}

并将其添加到JS文件中,就可以了!

And add this into JS file, it works!

那么,现在我堆积了为什么我的jQuery代码不起作用的原因?

So, now I'm stacked why my jQuery code not work?

推荐答案

jquery append函数将对象作为参数而不是字符串html. 因此,这应该可以解决您的问题,$("#userinfo").append($('<p>Test</p>'))

The jquery append function takes an object as parameter and not a string html. So this should solve your problem, $("#userinfo").append($('<p>Test</p>'))

这篇关于无法使用jQuery将HTML代码附加到一个div中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆