javascript - jQuery、函数 .html 正确语法

标签 javascript jquery

不知怎的,我遇到了语法问题。我这里有这段代码

$('#logoutput').html("<div id=\"loginbox\" class=\"boxgrid\">Username: <form action=\"\" method=\"post\"><input class=\"textfieldcss\" type=\"text\" name=\"loginname\" value="+$userip+"\">Password: <form action=\"\" method=\"post\"><input class=\"textfieldcss\" type=\"hidden\" name=\"loginpass\" value="+$userpw+"\"></div>");

如果内容只有:

$('#logoutput').html("<div id=\"loginbox\" class=\"boxgrid\">Username: <form action=\"\" method=\"post\"><input class=\"textfieldcss\" type=\"text\" name=\"loginname\">"

它没有向我显示错误。

这可能是因为我在 jQuery 函数中错误地实现了变量吗?

最佳答案

这不是您问题的真正答案,但它会帮助您减少问题:不要使用这样的字符串。至少使用一个模板。有很多库可以为您做模板,但至少可以做一些类似的事情:

<script type="text/html" id="mooTemplate">
  <div id="loginbox" class="boxgrid">
    Username:
    <form action="" method="post">
    <input class="textfieldcss" type="text" name="loginname" value="{{ userip }}">
    Password:
    <form action="" method="post">
    <input class="textfieldcss" type="hidden" name="loginpass" value="{{ userpw }}">
  </div>
</script>

然后将其交换:

var templateHTML = $("#mooTemplate").text()
                   .replace(/{{ userip }}/, userip)
                   .replace(/{{ userpw }}/, userpw);
$(target).html(templateHTML);

不过,不要自己动手,只需使用网络上提供的众多预制模板解决方案之一即可。我个人喜欢 nunjucks,但还有很多其他的。

关于javascript - jQuery、函数 .html 正确语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33509193/

相关文章:

jquery - 以编程方式设置 <select> 的值时,不会调用 Change 事件

javascript - 在没有预期点击的情况下触发了点击?

php - 如何通过ajax从服务器发送png图片到浏览器显示

javascript - 如何将客户端 HTML 导入 Gatsby/React?

javascript - 即使使用 math random,IE8 仍在缓存我的请求

jQuery 绑定(bind)问题

javascript - 忽略错误并继续在 IE 中运行 javascript?

javascript - 尝试建立一个模拟时钟,但它的小时针不能正常工作,帮我解决小时针代码

jquery - jVectorMap标签不可见,为什么?

javascript - 获取链接 url 的特定部分