避免 jquery 中的多个加载函数

Avoiding multiple load functions in jquery

我有一个 50 项的 ul。有没有什么方法可以不用写下面的50个?

$(function(){
$("#nav_a").on("click", function(){
    $("#main_text").load("pageA.html #main_text");  
});
$("#nav_b").on("click", function(){
    $("#main_text").load("pageB.html #main_text");  
});    
$("#nav_c").on("click", function(){
    $("#main_text").load("pageC.html #main_text");  
});

您可以像这样在所有这些元素中放置一个共同的 class:

<ul class="myElem" data-page="n">...

并在 jQuery 中:

$(document).on('click', '.myElem', function() {
  var page = $(this).attr('data-page');  //Get the page
  $('#main_text').load('page' + page + '.html #main_text');
});

使用 starts-with 选择器 ^=splitid 上获取字母:-

$(function() {
  $('[id^="nav_"]').on("click", function() {
    var letter = this.id.split('_')[1];
    $("#main_text").load("page" + letter + ".html #main_text");
  });
});

如果你想保留大写那么+ letter.toUpperCase() +

您可以使用 jQuery 中内置的 each() 和 eq() 函数。 参见示例:

Html:

<ul>
  <li>0</li>
</ul>

<ul>
  <li>1</li>
</ul>

Javascript:

var color = ['red', 'blue'];

$("ul").each(function(i) {
  $("ul:eq( " + i + " )").css("color", color[i]);
});

并根据您的情况进行如下更改:

var page = ['pageA.html', 'pageB.html', 'pageC.html'];

$("#nav ul").each(function(i) {
    $("ul:eq( " + i + " )").on( "click", function() {
      $("#main_text").load(page[i] + " #main_text");  
    });
});