0

クラスcurrentを持つアンカーのID属性を取得しようとしています。または、その親LIがクラスcurrentを持っています。

私はこのコードを試します:

    var terms = '';
    $('.product-tax li').each(function(){
        if ($(this).hasClass('current')) {
            terms += $(this).children('a').attr('id') + ':';
        } else if ($(this).children('a').hasClass('current')) {
            terms += $(this).children('a').attr('id') + ':';
        }
    });

しかし、それは機能せず、予期しない結果をもたらします。LIまたはアンカーの「現在」のクラスのIDをアンカー内で取得したいと思います。

基本的に、複数の.product-taxがあり、ユーザーが選択するため、それぞれを使用していますが、クラス「current」をLIまたはアンカーに追加できるため、確認する必要があります。このコードは機能しません。

助言がありますか?

HTML:

<div class="product-tax product-color">
    <h3>Choose color</h3>
    <ul>
        <li><a href="#" id="color-pink" style="background: Pink;border: 1px solid Pink;"></a></li>
    </ul>
</div>


<div class="product-tax product-size">
    <h3>Choose size</h3>
    <ul>
        <li><a href="#" id="size-2s">2(s)</a></li>
        <li><a href="#" id="size-3m">3(m)</a></li>
        <li><a href="#" id="size-4l">4(l)</a></li>
        <li><a href="#" id="size-5xl">5(xl)</a></li>
        <li><a href="#" id="size-6xxl">6(xxl)</a></li>
    </ul>
</div>
4

3 に答える 3

2

次のように、LI 要素のすべてのアンカーの子と、現在のクラスを持つすべての子を選択できます。

var terms = "";
$(".product-tax li.current > a, .product-tax li > a.current").each(function(){
    terms = terms + $(this).attr("id") + ":"
});
于 2012-09-05T15:02:36.537 に答える
1

これを試して

// get anchor with class current and anchor with parent li with class current
$('a.current,li.current > a').each(function(){
      alert(this.id);
});
于 2012-09-05T14:57:27.667 に答える
0
    var terms = '';
    $('.product-tax li').each(function(){
      if ($(this).hasClass('current')) {
        terms += $(this).attr('id') + ':';
      }
      var $anchors = $(this).children("a");
      $anchors.each(function(){
        if ($(this).hasClass('current')) {
          terms += $(this).attr('id') + ':';
        }
      });
    });
于 2012-09-05T15:04:46.660 に答える