1

我正在使用具有多个可切换的 div 的页面。此功能有效。添加了搜索功能,这也有效。

当前存在的页面问题:搜索栏放置在“默认” div 上,结果加载到栏下方的另一个 div 中,该 div 为空时不可见。结果 div 位于第一个默认 div 中。如果切换到另一个 div,则会丢失默认 div 并且无法恢复。

出于这个原因,我将搜索栏移到了其他切换链接所在的左侧导航。我还将搜索结果 div 从默认 div 中移出以“独立存在”。

我正在尝试做的事情:使搜索按钮显示带有结果的 div 并找到结果。基本上,将搜索功能集成到数组/切换功能中。搜索功能位于一个 .js 文件中,而切换功能位于另一个 .js 文件中。

我一直认为必须有一种方法可以让“onclick”从两个 .js 文件中调用,这样我就不必做一堆额外的工作来结合已经存在并单独工作的两个函数。我是一个通过示例学习的 Javascript 新手,但无法弄清楚这一点。我从未见过这样的工作示例,我的搜索也没有产生一个。

如果有任何帮助,我将不胜感激。希望我充分解释了这个问题。

编辑:这是我已经拥有的切换功能的代码。

var ids=new Array('a','b','c',[and so on--search results not added here yet]);

function switchid(id_array){
    hideallids();
    for( var i=0, limit=id_array.length; i < limit; ++i)
        showdiv(id_array[i]);
}

function hideallids(){
    for (var i=0;i<ids.length;i++){
        hidediv(ids[i]);
    }
}

function hidediv(id) {
    //safe function to hide an element with a specified id
    if (document.getElementById) { // DOM3 = IE5, NS6
        document.getElementById(id).style.display = 'none';
    }
    else {
        if (document.layers) { // Netscape 4
            document.id.display = 'none';
        }
        else { // IE 4
            document.all.id.style.display = 'none';
        }
    }
}

function showdiv(id) {//safe function to show an element with a specified id
    if (document.getElementById) { // DOM3 = IE5, NS6
        document.getElementById(id).style.display = 'block';
    }
    else {
        if (document.layers) { // Netscape 4
            document.id.display = 'block';
        }
        else { // IE 4
            document.all.id.style.display = 'block';
        }
    }
}

function initialize(){
    var t = gup("target");
    if( t )
    {
        switchid([t]);
    }
}

function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null ){
      return "";
  } else {
      return results[1];
  }
}

提前致谢!

4

1 回答 1

0

当您的切换功能代码被加载时,这些功能将在全局范围内声明。当您加载搜索函数时,它们也在全局范围内。由于它们在同一范围内,即使它是不同的文件,如果您在具有切换功能的文件之后包含具有搜索功能的文件,则切换功能可以由您的搜索功能使用。

TL;博士

function search(...) {
    // do your search stuff
    // when you get a result ID, toggle it from here
    hideallids();
    showdiv(id);
}

我强烈建议您使用有意义的名称、对象作为命名空间来组织您的代码,并使用 CamelCase 或下划线来标​​记标识符中的单词边界。例如:

window.ZESearch = {
    'initialize' : function() { ... },
    'search': function() {
        // Find the node with the desired result
        ZESearch.showResult(id);
    },
    'hideAllResults': function() { ... },
    'hideResult' : function(id) { ... },
    'showResult' : function(id) { ... },
    ...
};
ZESearch.initialize();

由于您刚刚学习,因此我避免了this关键字的复杂性,提供了一种创建对象以保持代码井井有条的简单方法,但将对象添加到window其中以便您可以从代码中的任何位置获取它。

于 2012-10-13T03:34:37.153 回答