最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why doesn't innerHTML work on jQuery collections? - Stack Overflow

programmeradmin1浏览0评论

This function uses jQuery to modify the contents of a DOM element. What am I doing wrong?

function updateScore(score) {
  console.log("Test score is: " + score);
  $("#testScore").innerHTML = 'Current score is:' + score;
}

updateScore(1000);
<script src=".7.1/jquery.min.js"></script>

<p id="testScore">

This function uses jQuery to modify the contents of a DOM element. What am I doing wrong?

function updateScore(score) {
  console.log("Test score is: " + score);
  $("#testScore").innerHTML = 'Current score is:' + score;
}

updateScore(1000);
<script src="https://cdnjs.cloudflare./ajax/libs/jquery/3.7.1/jquery.min.js"></script>

<p id="testScore">

The log message shows up, but nothing else does. I have a <p> with the id testScore, but it doesn't change when I run the function. Why?

Share Improve this question edited Dec 1, 2024 at 15:04 dumbass 27.3k4 gold badges37 silver badges74 bronze badges asked Nov 14, 2010 at 21:58 Elliot BonnevilleElliot Bonneville 53.4k23 gold badges100 silver badges124 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 10

Try .html() on a jQuery object. innerHTML is for DOM-Elements.

$("#testScore").html('Current score is: '+ bucket.score);

If, for some reason, you really want to use innerHTML, you can convert the jQuery Object back to its DOM variant, for example using [0] or .get(0). Call like this, then:

$("#testScore")[0].innerHTML ='Current score is: '+ bucket.score

But I don't see why you would want to do that - since you're already writing in jQuery, there's no need to fallback to DOM methods that have a perfectly fine jQuery equivalent.

function updateScore() {
    alert("Test score is: " + bucket.score);
    $("#testScore").text('Current score is: ' + bucket.score);
}

try

$("#testScore").innerHTML('Current score is: + bucket.score');

The jQuery objects do not support assignment to the attributes. (Its a Javascript limitation) You have to call the function with a parameter to set something.

发布评论

评论列表(0)

  1. 暂无评论