如何优化我的加载JQuery函数?

时间:2016-09-09 11:30:44

标签: javascript php jquery

我有侧边栏,其中包含很多标题。我不想为他们所有人写一个函数。这是一个代码:

$("#menu_documentations").click(function () {
$("#sites").load("documentations/documentations_doc.php");
$("html, body").animate({ scrollTop: 0 }, "slow");
return false;
 });

侧边栏的ID总是看起来像“#menu_xyz”,加载php使用相同的“xyz_doc.php”。

我怎样才能避免逐一写作?!

2 个答案:

答案 0 :(得分:3)

使用url的类和数据属性 HTML:

<a class="load-ajax" href="#" data-url="coustom-page-name.html">Link</a>

<a class="load-ajax" href="coustom-page-name.html">Link</a>

JS:

$(".load-ajax").click(function () {
var url = $(this).attr('data-url');//$(this).attr('href');
$("#sites").load(url);
$("html, body").animate({ scrollTop: 0 }, "slow");
return false;
 });

答案 1 :(得分:0)

以下内容可行(与madalin相同,除了我只使用数据属性本身来定位元素而不是添加另一个类):

HTML:

 <button data-get-page="documentations/documentations_doc.php">click me </button>

JS:

$(document).on('click','[data-get-page]',function() {
  var $this=$(this);
  var url=$this.data('get-page');
  $("#sites").load(url);
  $("html, body").animate({
    scrollTop: 0
  }, "slow");
  return false;
});