我有以下HTML,我试图找出如何做一些jQuery。我想采取以下内容,只有在页面上找到id为myDatatable的表时才执行以下两行代码。我怎么会这样,我认为这将是回流到父母,然后尝试做一个find(),但我不确定我会如何正确的条件。
$('.panel-title').addClass('pull-left');
$('.panel-heading').append('<div class="pull-right" style="padding-top:5px;"><a class="btn btn-sm btn-default btn-block" href="'+ window.location.href +'/create">Add New</a></div>');
<!-- Begin: Content -->
<section id="content">
<div class="row">
<div class="col-md-12">
<div class="panel panel-visible">
<div class="panel-heading">
<div class="panel-title hidden-xs">
<span class="glyphicon glyphicon-tasks"></span>Users
</div>
</div>
<div class="panel-body pn">
<table class="table table-striped table-bordered table-hover" id="myDatatable" cellspacing="0" width="100%">
...table data here
</table>
</div>
</div>
</div>
</div>
</section>
答案 0 :(得分:2)
只需检查页面上是否有id = myDatabase
的表格<!-- Begin: Content -->
<section id="content">
<div class="row">
<div class="col-md-12">
<div class="panel panel-visible">
<div class="panel-heading">
<div class="panel-title hidden-xs">
<span class="glyphicon glyphicon-tasks"></span>Users
</div>
</div>
<div class="panel-body pn">
<table class="table table-striped table-bordered table-hover" id="myDatatable" cellspacing="0" width="100%">
...table data here
</table>
</div>
</div>
</div>
</div>
</section>
<script>
if($('#myDatatable').length>0){
$('.panel-title').addClass('pull-left');
$('.panel-heading').append('<div class="pull-right" style="padding-top:5px;"><a class="btn btn-sm btn-default btn-block" href="'+ window.location.href +'/create">Add New</a></div>');
}
</script>
你也可以像这样使用jQuery的has
函数:
if($('#content').has('#myDatabase').length>0){
$('.panel-title').addClass('pull-left');
$('.panel-heading').append('<div class="pull-right" style="padding-top:5px;"><a class="btn btn-sm btn-default btn-block" href="'+ window.location.href +'/create">Add New</a></div>');
}