繁体   English   中英

在javascript函数中使用jQuery格式化HTML

[英]Formatting HTML with jQuery inside a javascript function

我正在尝试根据用户按下的按钮更新页面上的数字。 我有它工作,但当数字更新时,文本不再像在<code> </ code>块中那样格式化。 这是我正在使用的代码减去控制格式的任何努力:

<script>
    var countUp = function() {
        $("#num").html(parseInt($("#num").html()) + 1);
        $("#textWithNumInIt").html("The number is now"+$("#num").html() );
    }
</script>

<p id="textWithNumInIt"><code>The number is 0</code></p>

我已经尝试将<code> </ code>标记放在jQuery中,包含和不包含转义字符。 我尝试使用.val()和.text()来设置文本,以便单独保留格式。 我尝试使用数字本身的范围,但随后值甚至没有更新。

这是我第一次在javascript函数中使用jQuery更改HTML,所以麻烦可能与此有关。 任何帮助都会很棒,如果你有完全不同的方法来做这个,请分享。

当您编辑textWithNumInIt段落的内容时,该段落中的<code>标签也会自然被替换。 这应该工作:

$("#textWithNumInIt").html("<code>The number is now "+$("#num").text()+"</code>" );

也许试试这个 -

$('#textWithNumInIt code').html("The number is now "+$("#num").text() )

当你解析它时,它会被转换成纯文本, <code>包装器就会消失。 使用这个,你将走在你的道路上。

var countUp = function() {
    var t = parseInt($("#num").text()) + 1);//using text() to avoid any unintentional html tag issues
    $("#num").html(t);
    $("#textWithNumInIt").html("<code>The number is now "+t+"</code>" );
}

或者你可以通过简单的编辑继续你的代码。

var countUp = function() {
    $("#num").html(parseInt($("#num").html()) + 1);
    $("#textWithNumInIt code").html("The number is now"+$("#num").html() );
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM