【问题标题】:How to select the content inside a div using javascript/jquery如何使用 javascript/jquery 选择 div 内的内容
【发布时间】:2012-02-09 13:48:22
【问题描述】:

我相信答案可能很简单,但我无法通过搜索找到答案。

我想做的是使用 jquery 更改 div 的内容。目前我正在使用这个(它确实有效,但不是最优雅的解决方案)

选择它的最佳方法是什么?

$(document).ready(function () {
    $("#score-once").click(function ()  {
        var numRand = parseInt(Math.floor(Math.random()*2));
        var currValue = parseInt($("#scored").text());
        var newValue = (currValue + numRand);
        $("#scored").replaceWith("<p id=scored>" + newValue + "</p>")
        currValue = undefined;
        newValue = undefined;
    });     
});

和html

        <div id="sidebar">
            Goals Scored<br />
            <p id="scored">0</p>
            Goals Missed<br />
            <p>0</p>
        </div>

【问题讨论】:

  • 你怎么知道它不是最优雅的?对我来说看起来不错:-)
  • 必须替换整个段落标签,而不仅仅是替换内容+未定义变量(我什至不确定我必须这样做!)。或者我只是过度批评我自己的工作;)
  • 取消定义你不必做的事情。其余的还可以。继续下一个任务:-)
  • 你有点哈哈。如果 p ;)
  • 我唯一建议使用这个而不是replaceWith - ` $("#scored").text(newValue);`

标签: javascript jquery syntax selector


【解决方案1】:

使用 jQuery 的 .html() 函数应该可以解决问题。

$("#scored").html(newValue);

【讨论】:

    【解决方案2】:

    这是一个小小的改进:

    $(document).ready(function () {
        $("#score-once").click(function ()  {
            var numRand = parseInt(Math.floor(Math.random()*2));
            var currValue = parseInt($("#scored").text());
            var newValue = (currValue + numRand);
            $("#scored").text(newValue)
        });     
    });
    

    可能没有比这更好的了 :-)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-04
      • 1970-01-01
      • 1970-01-01
      • 2015-12-06
      • 1970-01-01
      • 1970-01-01
      • 2017-10-09
      相关资源
      最近更新 更多