简体   繁体   English

如何优化我的加载JQuery功能?

[英]How to optimize my loading JQuery function?

I have sidebar which contains a lot of titles. 我有侧边栏,其中包含很多标题。 I don't want to write for all of them a function. 我不想为他们所有人写一个函数。 Here is a code for one : 这是一个代码:

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

The sidebar's id always look like "#menu_xyz" and the loading php using the same "xyz_doc.php". 侧边栏的ID总是看起来像“#menu_xyz”,加载php使用相同的“xyz_doc.php”。

How can I avoid to write one by one ?! 我怎么能避免一个一个地写?

use a class and a data attribute for the url html: 使用url html的类和数据属性:

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

or 要么

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

js: 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;
 });

The below would work (same as madalin's except I would just use the data attribute itself to target the elements rather than adding another class): 下面的方法是可行的(与madalin相同,除了我只使用data属性本身来定位元素而不是添加另一个类):

HTML: HTML:

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

JS: 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;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM