在.html()标记内格式化html

learning_to_swim

在JavaScript回调函数中,我在页面上显示成功/失败消息。当我将HTML内容放在一行中(如以下代码中所示)时,将添加该消息,并且一切正常!

$('#message').html("<div class='alert alert-danger'><i class='fa fa-times-circle fa-2x'>Incorrect!</div>")

但是,当我尝试格式化HTML以获得更好的可读性时,如下所示-没有任何反应,并且在Firebug控制台中没有看到我要添加的消息,也没有看到任何错误消息。

 $('#message').html("<div class='alert alert-danger'>
                              <p><i class='fa fa-times-circle fa-2x'>
                                Incorrect! Yesterday was " + <%= @yesterday %> +
                             "</p>
                             <p>Click Next to continue.</p>
                         </div>")

我不确定问题是什么,我们将不胜感激!

编码消失了

对于任何复杂的HTML,请勿使用字符串连接,甚至不要使用字符串文字。它们是维护的噩梦。例如,您的i元素未终止:

您可以简单地使用具有所需HTML的虚拟脚本块:

<script type="text/template" id="mytemplate">
    <div class='alert alert-danger'>
               <i class='fa fa-times-circle fa-2x'>Incorrect!</i>
    </div>
</script>

并像这样使用:

$('#message').html($('#mytemplate').html());

type="text/template" 是无效值,浏览器将忽略此块(将其保留完整)。

对于您的复杂示例,您可以看到仍然可以注入ASP.Net内容,只是现在布局是显而易见的(并且在页面中,而不是在代码中,它所属的位置):

<script type="text/template" id="mytemplate">
   <div class='alert alert-danger'>
       <p><i class='fa fa-times-circle fa-2x'>
           Incorrect! Yesterday was <%= @yesterday %>
          </i>
       </p>
       <p>Click Next to continue.</p>
   </div>
</script>

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章