2

私はたくさんのdivを持っています。

<div id="container">

  <div><a>One</a></div>
  <div><a>Two</a></div>
  <div><a>Three</a></div>
  <div><a>Four</a></div>

</div>

Javascript と jQuery を使用して要素がクリックされた div を確認する必要があります。

要素がクリックされdiv (1 番目、2 番目、3 番目、または 4 番目)に基づいて、整数を返す必要があります。

4

3 に答える 3

3
var divs = $('#container').on('click', 'a', function() {
   alert(divs.index(this.parentNode));
}).children('div');
于 2012-12-29T12:35:40.580 に答える
1

を使用.parent()して から を取得してdivから、aを使用.index()してその兄弟間の位置を取得する必要があります。

$('#container a').click(function(){
   var self = $(this),
       clickedDiv = self.parent(),
       index = clickedDiv.index();

   alert(index); // first is 0, second is 1 etc...
});

それほど冗長ではない構文は次のようになります。

$('#container a').click(function(){
   var index = $(this).parent().index();

   alert(index); // first is 0, second is 1 etc...
});
于 2012-12-29T12:33:50.460 に答える
0

Array.prototype.forEach.querySelectorAllおよびを使用したネイティブ JavaScript 実装.addEventListener

<a>1つに1つしかない場合<div>

Array.prototype.forEach.call( // for each
    document.querySelectorAll('#container a'), // <a> in #container
    function (elm, idx, arr) { // get it's info (index etc.) then
        elm.addEventListener('click', function () {console.log(idx);}, false);
            // make clicking it log it's index
    }
);

<a>または、あたりに多くの s がある場合<div>

Array.prototype.forEach.call( // for each
    document.querySelectorAll('#container div'), // <div> in #container
    function (elm, idx, arr) { // get it's info (index etc.) then
        Array.prototype.forEach.call( // loop over each
            elm.querySelectorAll('a'), // <a> in that <div>
            function (a_elm, a_idx, a_arr) { // and
                a_elm.addEventListener('click', function () {console.log(idx);}, false);
                    // make clicking it log the index of the <div>
            }
        );
    }
);

ログに記録されたインデックスは最初から始まることに注意0してください。

于 2012-12-29T18:37:33.110 に答える