【发布时间】: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