2017-04-02 5 views
0

I持っ以下:それぞれ固有の情報私はこれらのいずれかのボタンがあるときになるようにそれを作るしようとしている取得値

<div class="button"> 
    <div id="first"> 
     Johny 
    </div> 
    <div id="second"> 
     Dog 
    </div> 
    <div id="third"> 
     Pasta 
    </div> 
</div> 
<div class="button"> 
    <div id="first"> 
     Bob 
    </div> 
    <div id="second"> 
     Cat 
    </div> 
    <div id="third"> 
     Noodles 
    </div> 
</div> 
    . 
    . 
    . 

を持っているボタンのdivのの束私は内側のdivの値をチェックすることができます。例えば

$('.button').on('click', function() { 
    // Check to see if the text of the 'first' div is 
    // johnny or bob or something else 
}); 
+0

'$(this).children()'はあなたに現在のdivのすべての子を与えます。これで、その配列を反復してテキストを取得できます –

答えて

0

あなたが代わりにthat.Exのためのクラスを使用し、page.Soで複数の要素に同じIDを使用することはできませんまず第一に:

<div class="button"> 
    <div class="first"> 
     Johny 
    </div> 
    <div class="second"> 
     Dog 
    </div> 
    <div class="third"> 
     Pasta 
    </div> 
</div> 
<div class="button"> 
    <div class="first"> 
     Bob 
    </div> 
    <div class="second"> 
     Cat 
    </div> 
    <div class="third"> 
     Noodles 
    </div> 
</div> 

今JavaScriptで:

$('.button').on('click', function() { 
    var first=this.getElementsByClassName("first")[0];//gets first element of this button 

var second=this.getElementsByClassName("second")[0]; 

var third=this.getElementsByClassName("third")[0]; 

//Now you do what ever you want 
}); 
0

拳のdivのテキストを取得するために$(this).children(":first").text()を試してみてください

0
<script> 
    $('.button').on('click', function() { 
     if ($(this).find("#first").html().trim() == "Johny") { 
      console.log("The first div is Johny"); 
     } else if ($(this).find("#first").html().trim() == "Bob") { 
      console.log("The first div is Bob"); 
     } 
    }); 
</script> 
0

各divに独自のクリックハンドラを与えるのはどうですか?

<script type="text/javascript"> 
    var bchildren = $('.button').children(); 
    $(bchildren).click(function() { 
     console.log($(this).html()); 
    }); 
    } 
</script>