Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/364.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何优化我的加载JQuery函数?_Javascript_Php_Jquery - Fatal编程技术网

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

Javascript 如何优化我的加载JQuery函数?,javascript,php,jquery,Javascript,Php,Jquery,我有一个侧边栏,里面有很多标题。我不想为他们所有人写一个函数。下面是一个代码: $("#menu_documentations").click(function () { $("#sites").load("documentations/documentations_doc.php"); $("html, body").animate({ scrollTop: 0 }, "slow"); return false; }); 侧边栏的id看起来总是像“#menuxyz”,加载的php使用相同的

我有一个侧边栏,里面有很多标题。我不想为他们所有人写一个函数。下面是一个代码:

$("#menu_documentations").click(function () {
$("#sites").load("documentations/documentations_doc.php");
$("html, body").animate({ scrollTop: 0 }, "slow");
return false;
 });
侧边栏的id看起来总是像“#menuxyz”,加载的php使用相同的“xyz_doc.php”


我怎么能避免一个接一个地写

为url使用类和数据属性 html:

下面的方法会起作用(与madalin的方法相同,只是我会使用data属性本身来定位元素,而不是添加另一个类):

HTML:


为URL使用类和数据属性如果我们使用
a
标记,不要忘记
事件。preventedfalt()
。@高兴的是,老实说,我已经习惯了
preventDefault()
我甚至没有注意到
返回false
:)
<a class="load-ajax" href="#" data-url="coustom-page-name.html">Link</a>
<a class="load-ajax" href="coustom-page-name.html">Link</a>
$(".load-ajax").click(function () {
var url = $(this).attr('data-url');//$(this).attr('href');
$("#sites").load(url);
$("html, body").animate({ scrollTop: 0 }, "slow");
return false;
 });
 <button data-get-page="documentations/documentations_doc.php">click me </button>
$(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;
});