在打开 jQuery 的情况下调用多个函数.(“咔嚓”)

Calling multiple functions with jQuery on.('click'...)

本文关键字:函数 咔嚓 jQuery 调用 情况下      更新时间:2023-09-26

我有两个并排的div。左侧(方法(div 包含链接,单击这些链接时,使用".load"从外部 html 文件将一些文本加载到右侧(描述(div 中。我还有一些脚本可以将"方法"div 的高度与"描述"div 的高度相匹配,我已将其放入函数中。

我的问题是我无法让高度匹配函数与文本加载脚本在同一单击上运行。目前,单击链接会根据需要加载文本,但在再次单击链接之前不会发生高度匹配。

我是javascript/jQuery的新手,所以对任何和所有解决方案都持开放态度,包括完全重写代码,如果这是它所需要的。

代码可以在这里看到"工作":http://plnkr.co/edit/1CW1a7XNu73Kyo4xPMyg?p=preview

$(document).ready(function() {
    
    function matchDesc() {
        var hh = document.getElementById("descriptions").offsetHeight;         
        document.getElementById("methods").style.height = hh + "px";
    }
     $("#content").on('click', '#link', function(){
        var str = $(this).attr('class');
        var sect = str.slice(-1);
        $("#descriptions").load("descriptions.html #description-" + sect);
        $("#methods li a").css('color','#3164BE');
        $(this).css('color','red');
        matchDesc();
    });                     
                      
    window.onload = function() {
    matchDesc();
        }
});

修复了此处的代码:http://plnkr.co/edit/lcAmQ9wcIGLJ9JjDi3HD?p=preview

$(document).ready(function() {
  function matchDesc() {
    var hh = document.getElementById("descriptions").offsetHeight;
    document.getElementById("methods").style.height = hh + "px";
  }
  $("#content").on('click', '.link', function() {
    var str = $(this).attr('id');
    var sect = str.slice(-1);
    $("#descriptions").load("descriptions.html #description-" + sect,
      function() {
        $("#methods li a").css('color', '#3164BE');
        $(this).css('color', 'red');
        matchDesc();
      });
  });
  window.onload = function() {
    matchDesc();
  }
});

正如 arun 所说,加载事件完成后需要调用 do matchDesc。

看到这个叉子: http://plnkr.co/edit/x4Ge7Xy3DRuQWlM9McxD?p=preview

听从阿伦的建议,改了比赛;使用window.onload时,不要使用在读取函数后立即进行函数调用的matchDesc();。使用 window.onload = matchDesc 将允许它在加载其他所有内容后加载。

$(document).ready(function() {
    function matchDesc() {
        var hh = $('#descriptions').outerHeight()        
        return $('#methods').outerHeight(hh);
    }
     $("#content").on('click', '.link', function(){
        var str = $(this).attr('id');
        var sect = str.slice(-1);
        $("#descriptions").load("descriptions.html #description-" + sect, function() { 
            $("#methods li a").css('color','#3164BE');
            $(this).css('color','red');
            matchDesc();
        });
    });                     
    window.onload = matchDesc;
});