简化 jQuery DOM 请求



我想将我的代码简化为一个完整的步骤函数。由于它具有相同的属性和函数,我不知道究竟是什么调用函数将它们全部合并到一个操作中。

$('a[data-user="add"]').click(function(event) {
  event.preventDefault();
  $('.list-unstyled li').removeClass('active');
  $('section.col-lg-8').replaceWith(formAdd);
  $('.form-custom').load('includes/pages/admin/admin-user-add.php');
  subHash = this.hash;
});
$('a[data-user="settings"]').click(function(event) {
  event.preventDefault();
  $('.list-unstyled li').removeClass('active');
  $('section.col-lg-8').replaceWith(formAdd);
  $('.form-custom').load('includes/pages/admin/admin-user-settings.php');
  subHash = this.hash;
});

我认为用单独的逗号包含它将是一个好主意,但事实并非如此。 它将视图默认为我的第一次加载。

尝试抓取两个用逗号分隔的选择器,然后使用 jQuery 的 .attr() 函数填写正确的管理页面:

$('a[data-user="settings"],a[data-user="add"]').click(function(event) {
  event.preventDefault();
  $('.list-unstyled li').removeClass('active');
  $('section.col-lg-8').replaceWith(formAdd);
  $('.form-custom').load('includes/pages/admin/admin-user-'+$(this).attr('data-user')+'.php');
  subHash = this.hash;
});

最新更新