使用.content().get().nodevalue;后在firebug中获取类型错误;

Getting a typeerror in firebug after using .content().get().nodevalue;

本文关键字:获取 取类型 错误 firebug 后在 get nodevalue 使用 content      更新时间:2023-12-04

我正试图从每个html LI中获取一个数字在LI中有如下html代码所示的链接:

<div id="summary">
        <ul class="nobullets last-child">
           <li><a href="#">Blog Posts</a> (9)</li>
           <li><a href="#">Photos</a> </li>
           <li><a href="#">Discussion</a> (10)</li>
       </ul>
</div>

正如你所看到的,每个LI中的一些链接旁边都有数字我只想得到那些有数字的(博客文章),然后把这个数字存储到一个变量中,如果他们没有数字,只会在变量中加一个0。

但这是我的jquery代码:

var getblog;
var getphoto;
      //blogs
      if($('#summary').find('ul li:first-child').contents().get(1).nodeValue != 'undefined'){
        getblog = $('#summary').find('ul li:first-child').contents().get(1).nodeValue;
        getblog = parseFloat( getblog.substr(2) );
      }
      else{
        getblog = '0';
      }

      //photos
      //+ li to get the second child
      if($('#summary').find('ul li:first-child + li').contents().get(1).nodeValue != 'undefined'){
        getphoto = $('#summary').find('ul li:first-child + li').contents().get(1).nodeValue;
        getphoto = parseFloat( getphoto.substr(2) );
      }
      else{
         getphoto = '0';
      }

firebug向我抛出了一个错误:类型错误:$("#summary").next().find("ul-li:第一个子+li").contents().get(1)未定义

这是小提琴http://jsfiddle.net/hP3Wq/

博客显示9有效,但照片显示的是NaN,而不是0

我不确定您的代码都在努力实现什么,但如果它只是匹配,例如可能很明显的(3)前缀,您可以按如下方式使用.text().match():http://jsfiddle.net/hP3Wq/2/.

$(document).ready(function(){
    // use a generic function so as not to repeat things
    var getNumber = function(index) {
        return ($("#summary li")  // from the lis
                .eq(index)        // a specific li from the lis
                .contents()       // its contents
                .last()           // number is apparent in the last text node
                .text()           // its text
                // match it against a regexp defining "(somenumbers)";
                // in case of no match, use a dummy array with zeroes
                // (this defines the fallback)
                .match(/'(('d*)')/) || [0, 0]
               )[1];
    };
    var getblog = getNumber(0);
    var getphoto = getNumber(1);
    $('#summary').after(getblog + '<br>' + getphoto);
});