【问题标题】:Formatting HTML with jQuery inside a javascript function在 javascript 函数中使用 jQuery 格式化 HTML
【发布时间】:2013-02-12 16:41:41
【问题描述】:

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

<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>

我尝试将 标记放入 jQuery 中,有或没有转义字符。我尝试使用 .val() 和 .text() 来设置文本,以保持格式不变。我尝试在数字本身周围使用跨度,但该值甚至没有更新。

这是我第一次在 javascript 函数中使用 jQuery 更改 HTML,所以问题可能与此有关。任何帮助都会很棒,如果您对完全不同的方法有建议,请分享。

【问题讨论】:

标签: javascript jquery html


【解决方案1】:

当您编辑textWithNumInIt 段落的内容时,该段落内的&lt;code&gt; 标记自然也会被替换。这应该有效:

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

【讨论】:

  • 我已经尝试过了,但没有成功。我只是尝试将 标签包裹在它周围,然后粗体出现了。我正在使用的框架可能会阻止在 javascript 中使用某些标签?
  • 不知道。 As EP pointed out, a self-contained example works fine,所以你需要向我们提供一个它不起作用的例子,然后我们才能尝试找出原因。
【解决方案2】:

也许试试这个 -

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

【讨论】:

    【解决方案3】:

    当您解析它时,它会被转换为纯文本,并且 &lt;code&gt; 包装器消失了。使用它,您将走上自己的道路。

    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() );
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-10
      • 1970-01-01
      • 2014-01-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多