Troubles sliding multiple dynamic sections in a page

时间:2016-04-25 09:36:43

标签: javascript jquery

I have this piece of HTML

@if (Model.xxxs != null)
{
  int PeriodiCnt = 0;
  <div class="box">
    @foreach (xxxModel xxx in Model.xxxs)
    {
      PeriodiCnt++;
      <div class="box">            
        <div class="box-header show_hide" onclick='DoToggle("@PeriodiCnt")'></div>
        <div class="box-content slidingDiv" id="B+@PeriodiCnt.ToString()">
        ...
        </div>
      </div>
    }
  </div>
}

and this Javascript

function DoToggle(PeriodiCnt)
{
  var nome = "#B" + PeriodiCnt.toString();
  $(nome).slideToggle();
}

I don't know how many sections will be on the page, and would like to "open / close" the sections clicking on the box header. Usually, when I do the same thing with STATIC code, it works. Now, this is my first "dynamic" attempt, I've spent hours trying, but nothing works.

Someone can help?

1 个答案:

答案 0 :(得分:0)

As you are using use it to subscribe events, You can use Event Delegation by using .on() method delegated-events approach, when generating elements dynamically.

General Syntax

$(document).on('event','selector',callback_function)

Example

$(document).on('click', ".show_hide", function(){
    $(this).next('.slidingDiv').slideToggle();
});

In place of document you should use closest static container.

$(function() {
  //Event binding
  $(".container").on('click', ".show_hide", function() {
    $(this).next('.slidingDiv').slideToggle();
  });

  //Dynamically genearte html
  var container = $('.container');
  for (var i = 0; i < 10; i++) {
    var div = $('<div />', {
      "class": 'box'
    });
    div.append($('<div />', {
      "class": 'box-header show_hide'
    }).text('Header ' + i));
    div.append($('<div />', {
      "class": 'box-content slidingDiv'
    }).text('box-content ' + i));

    container.append(div);
  }

});
.box-content {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
</div>