使用JavaScript将HTML插入标记

时间:2013-07-03 10:25:00

标签: javascript jquery html

我正在尝试访问代码中h4元素内部的元素时遇到JavaScript / jQuery问题。我这样做是因为我想动态地向用户显示每个“h4”部分中有多少指南。对于PC部分,它应显示“4个评论可用”,对于Xbox One部分,它应显示“3个评论可用”。但是,两者都说“评论可用”,我假设它是因为我没有正确使用jQuery函数。这是HTML代码:

  <h4><li class="console">PC (<span class="number"></span> reviews available)</li></h4>
  <div class="gameList">
      <ul>
          <li class="game"><a href="#">Guide #1</a></li>
          <li class="game"><a href="#">Guide #2</a></li>
          <li class="game"><a href="#">Guide #3</a></li>
          <li class="game"><a href="#">Guide #4</a></li>
      </ul>
  </div>
  <h4><li class="console">Xbox One (<span class="number"></span> reviews available)</li></h4>
  <div class="gameList">
      <ul>
          <li class="game"><a href="#">Guide #1</a></li>
          <li class="game"><a href="#">Guide #2</a></li>
          <li class="game"><a href="#">Guide #3</a></li>
      </ul>
  </div> 

这是jQuery / JavaScript代码:

$("h4").each(function() {
    var node = $(this).children().children(); // gets node that has "number" class  
    var count = $(this).next().children().children().length; // gets number of li tags
    node.innerHTML = count;
});

我测试了它是否通过使用JavaScript的alert函数正确获取正确的节点和计数,但由于某种原因,node.innerHTML = count将不会在元素中正确显示“content”的内容。相反,它只显示一个空白。有谁知道为什么?

6 个答案:

答案 0 :(得分:1)

它是一个jquery对象而不是DOM ...使用这个......

node.html(count);

答案 1 :(得分:1)

使用find()更清晰,更易读

$("h4").each(function() {
   var $this=$(this);
    var node = $this.find('.number'); 
   var count = $this.next().find('li').length; // gets number of li tags
   node.text(count);  //or html()
}); 

,您li中的HTML h4无效,请确保更改 working fiddle here

答案 2 :(得分:1)

node是一个jQuery对象。它没有“innerHTML”。相反,您可以使用以下其中之一:

node.html(count);
node.get(0).innerHTML = count;

node.get(0)将从jQuery中为您提供第一个DOM对象。

一个好的做法是使用$(例如$node)为所有jQuery对象添加前缀或后缀,这样您就可以始终知道变量是否是jQuery对象。

答案 3 :(得分:0)

请勿使用.children().children()

只有一个.children()会这样做。

$(this).children('.game');

innerHTML也是普通的javascript。使用.html(value)作为node是JQuery对象。

$("h4").each(function() {
    var node = $(this).children('.number');
    var count = $(this).next().children('li').length;
    node.html(count);
});

对JQuery API的引用:

.html()

.children()

答案 4 :(得分:0)

$("h4").each(function() {
   var $spanNumber = $('.console .number', this),
       gameListCount = $(this).next().find('ul li').size();

   $spanNumber.text(gameListCount)
});

答案 5 :(得分:0)

您也可以使用它,

$("h4").each(function() {
    var node = $(this).find('.number'); 
   var count = $(this).next().find('.game').length;
   node.html(count);
});