如何在文档准备函数中调用变量的click函数

how to call click function of variable in document ready function?

本文关键字:函数 调用 click 变量 文档      更新时间:2024-04-24

我想在文档加载功能的菜单1上触发我的点击事件。由于我在菜单上有很多函数,我把它分配给了一个变量。并对该变量调用了click事件。但它不起作用。

$(document).ready(function () {
    var $menuone = $('#menu1');
    var $menutwo = $('#menu2');
    var $menuthree = $('#menu3');
    var $menufour = $('#menu4');
    $menuone.trigger("click");
    $("#menuone").click(function () {
        $("#frm1").show();
        $("#frm3").hide();
        $("#frm4").hide();
        $("#frm2").hide();
        $(this).css({
            border: "2px solid #A69A8F",
            "border-bottom-width": "0",
            background: "#F7F7F7",
            color: "#0D638B;"
        });
        $(this).children().css({
            color: "#0D638B",
            "font-weight": "bold"
        });
    });
    $menutwo.click(function () {
        $menuone.removeAttr('style');
        $menuone.children().removeAttr('style');
        $("#frm1").hide();
        $("#frm3").hide();
        $("#frm4").hide();
        $("#frm2").show();
        $(this).css({
            border: "2px solid #A69A8F",
            "border-bottom-width": "0",
            background: "#F7F7F7",
            color: "#0D638B;"
        });
        $(this).children().css({
            color: "#0D638B",
            "font-weight": "bold"
        });        
    });
});

浏览器逐行运行您的JavaScript。因此,您对$("#menuone").click的绑定在触发单击时没有附加。

解决方案:

$( document ).ready(function() {
    var $menuone = $('#menu1');
    var $menutwo = $('#menu2');
    var $menuthree = $('#menu3');
    var $menufour = $('#menu4');
    $("#menuone").click(function () {
      $("#frm1").show();
      $("#frm3").hide();
      $("#frm4").hide();
      $("#frm2").hide();
      $(this).css({border:"2px solid #A69A8F","border-bottom-width":"0", background: "#F7F7F7",color:"#0D638B;"});
      $( this ).children().css({color: "#0D638B","font-weight":"bold"} );
    });
    $menutwo.click(function () {
      $menuone.removeAttr( 'style' );$menuone.children().removeAttr( 'style' );
      $("#frm1").hide();
      $("#frm3").hide();
      $("#frm4").hide();
      $("#frm2").show();
      $(this).css({border:"2px solid #A69A8F","border-bottom-width":"0", background: "#F7F7F7",color:"#0D638B;"});
      $( this ).children().css({color: "#0D638B","font-weight":"bold"} );
    });
    // Put it here
    $menuone.trigger("click");
});

顺便说一下,你的$menuone不是$("#menuone"),而是$("#menu1"),我猜这是打字错误吗