dqjjw04440
dqjjw04440
2015-02-26 23:25
浏览 437

通过JQuery获取动态内容的ID

I'm creating some dynamic content tabs using PHP, one object on the tab is a datatable. I define the ID via PHP like this:

PHP:

echo '<table class="table table-striped table-bordered table-hover" id="'.$nospaces.'">';

The table loads the data perfectly however I'm having problems initializing the datatable for sorting and filtering. Normally on static tables I would just initialize it using the static ID but I can't do that in this case.

I thought I could do some jquery to listen to a tab click event and then grab the table ID and load it into the jquery datatables initialization but that isn't working either. I'm just getting an undefined alert:

JQuery:

<script>
    $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
    var row = $(this).closest('table').attr('id');
    alert(row);

    $(document).ready(function() {
    oTable = $('row').dataTable( {
       "sDom": '<"top"lf>rt<"bottom"ip><"clear">'

    });

    });
    });
</script>

Any help would be greatly appreciated! Thanks.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • doudou0111
    doudou0111 2015-03-02 18:31
    已采纳

    I ended up doing a mixture with some extra steps. Not the cleanest but it's working.

    First on the dynamic tab/table I created a variable for a new ID because I had the tab and the table ID the same:

    PHP:

    $tableid = $nospaces .'table';
    echo '<table class="table table-striped table-bordered table-hover" id="'.$tableid.'">';
    

    I then initialize (and destroy) the datatable on tab click like this:

    JQuery:

    $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
    tab = e.target.hash // newly activated tab
    tabtable = tab + 'table'
    
    $(document).ready(function() {
        oTable = $(tabtable).dataTable( {
            "sDom": '<"top"lf>rt<"bottom"ip><"clear">'
        });
    });
    $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
        oldtab = e.relatedTarget.hash
        oldtable = oldtab + 'table'
        $(oldtable).dataTable().fnDestroy();
        });
    });
    
    点赞 评论
  • dongxidui1227
    dongxidui1227 2015-02-27 00:24

    Is there any reason you can't still use the static ID?

    var staticID = '<?php echo $nospaces; ?>';
    
    $('#' + staticID).dataTable();
    
    点赞 评论
  • doudao1282
    doudao1282 2015-02-27 11:42

    I guess using the variable row would do the trick, instead of using the string 'row' :)

    var row = $(this).closest('table').attr('id');
    alert(row);
    
    $(document).ready(function() {
    oTable = $(row).dataTable( { //<--- here
      "sDom": '<"top"lf>rt<"bottom"ip><"clear">'
    });
    
    点赞 评论

相关推荐