为什么jquery切换不能在角度代码中工作

时间:2016-08-18 14:03:54

标签: jquery

为什么按钮在<tr ng-repeat="Emp in John track by $index">下无法切换?

<script>
    $(document).ready(function () {
      $("#tab").hide()
       $("#btn1").click(function () {
            $("#tab").toggle();
        })  })

</script>

HTML:

<div ng-controller="MyCntrl">
        <table>
            <tr>
                <th>
                    <b>Employee Name</b>
                </th>
            </tr>
            <tr ng-repeat="Emp in John track by $index">
                <td>
                    <input type="button" id="btn1{{$index}}" value="click" ng-click="toggel($index)" />
                    {{Emp.Name}}
                    <table id="tab{{$index}}">
                        <tr>
                            <th>
                                <b>OrderId</b>
                            </th>
                        </tr>
                        <tr ng-repeat="Joy in Emp.order">
                            <td>
                                {{Joy.OrderId}}

                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
        </table>
    </div>

1 个答案:

答案 0 :(得分:1)

由于此处的html元素是动态添加的,因此您需要使用event delegation来注册事件处理程序,如:

// New way (jQuery 1.7+) - .on(events, selector, handler)
$(document).on('click', '[id^="btn1"]', function(event) {
    $(this).next('table').toggle();
});

修改

完整代码就像

$(document).ready(function() {
  $("#tab").hide();
  $(document).on('click', '[id^="btn1"]', function(event) {
    $(this).next('table').toggle();
  });
});