Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用javascript/jquery选择div中的内容_Javascript_Jquery_Syntax_Selector - Fatal编程技术网

如何使用javascript/jquery选择div中的内容

如何使用javascript/jquery选择div中的内容,javascript,jquery,syntax,selector,Javascript,Jquery,Syntax,Selector,我相信答案可能很简单,但我无法通过搜索找到答案 我想做的是使用jquery更改div的内容。目前我正在使用它(它确实有效,但不是最优雅的解决方案) 选择此选项的最佳方式是什么 $(document).ready(function () { $("#score-once").click(function () { var numRand = parseInt(Math.floor(Math.random()*2)); var currValue = par

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

我想做的是使用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;
    });     
});
$(文档).ready(函数(){
$(“#评分一次”)。单击(函数(){
var numRand=parseInt(Math.floor(Math.random()*2));
var currValue=parseInt($(“#评分”).text();
var newValue=(currValue+numRand);
$(“#评分”)。替换为(“

”+newValue+“

”) currValue=未定义; newValue=未定义; }); });
还有html

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

得分

0

没有进球
0


这里有一个小小的改进:

$(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)
    });     
});
它可能没有比这更好的了:-)

使用jQuery的
.html()
函数应该可以做到这一点

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

你怎么知道这不是最优雅的?在我看来还行:-)必须替换整个段落标记,而不仅仅是替换内容+取消定义变量(我甚至不确定我必须这么做!)。或者我只是过度批评了自己的工作;)不必进行定义。剩下的没问题。继续下一个任务:-)你有点搞笑。你也可以选择
$('#scored').html(“这里的内容”)更改内容(如果p;)我唯一的建议是用它代替
replacetwith
-`$(“#scored”).text(newValue)`