使用jQuery查找并替换代码块?

时间:2016-03-22 03:47:13

标签: javascript jquery

我有这个HTML:

<div class="group-sizing">
    <div class="form-group">
        <div>
            <h3>Guest <span>1</span> Welcome</h3>
            <div>
                <select id="level1"></select>
            </div>
        </div>
    </div>
</div>

我有这个功能:

var guestBlock = $(".group-sizing").html();
$("#guestNum").change(function(){
    var count = $(this).val();
    $(".group-sizing .form-group:gt("+(count-1)+")").remove();
    for (var i = $(".group-sizing .form-group").length; i < count; i++){
        $(guestBlock).find(?????????).html(i); //find and change span and id of select
        $(".group-sizing").append(guestBlock); //then print the block
    };
});

$(guestBlock).find()我希望找到<h3>的范围和<select>的ID。然后由我增加它们,但到目前为止我还没有能够得到它。它总是在这些空间中打印1。

1 个答案:

答案 0 :(得分:2)

您可以使用克隆来解决它,如

var $guestBlock = $(".group-sizing > .form-group").first().clone();
$("#guestNum").change(function() {
  var count = $(this).val();
  var $groups = $(".group-sizing > .form-group");
  $groups.slice(count).remove();
  for (var i = $groups.length; i < count; i++) {
    var $clone = $guestBlock.clone().appendTo('.group-sizing');
    $clone.find('h3 span').text(i + 1);
    $clone.find('select').attr('id', 'level' + (i + 1));
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="group-sizing">
  <div class="form-group">
    <div>
      <h3>Guest <span>1</span> Welcome</h3>
      <div>
        <select id="level1"></select>
      </div>
    </div>
  </div>
</div>


<select id="guestNum">
  <option>1</option>
  <option>2</option>
  <option>3</option>
  <option>4</option>
</select>