0

LI 内のすべての html 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 はエラーで私をスローしています: TypeError: $("#summary"). next(). find("ul li:first-child + li"). content(). get(1) is undefined

これがjsfiddle http://jsfiddle.net/hP3Wq/です

ブログには9が表示されていますが、写真には0ではなくNaNが表示されています

4

1 に答える 1

0

あなたのコードが何を達成しようとしているのかはわかりませんが、たとえば(3)明らかなプレフィックスと一致するだけの場合は、次のよう.text()に and.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);
});
于 2012-07-20T15:37:30.337 に答える