繁体   English   中英

JavaScript和Jquery:如何从JavaScript函数中调用jquery函数

[英]JavaScript and Jquery: How can you call a jquery function from within a javascript function

我有一个按钮,单击后会将变量发送到javascript函数。 当变量等于“ link”时,我想调用一个名为makeLink()的jQuery函数。

这就是我所拥有的:

function getText(change)
{
   if(change == "link")
   {
      //call jquery function called makeLink()

   }

}

这是我的jquery函数,它使用表单创建模式弹出窗口:

$(document).ready(function(){

function makeLink() {
    if ($("#makeALinkModalPopup").is(":hidden")){
    $("#makeALinkModalPopup").fadeIn("slow");

     $("#backgroundPopup").css({  
        "height": document.documentElement.offsetHeight

      });

    $("#backgroundPopup").css({"opacity": "0.7"});
    $("#backgroundPopup").fadeIn("slow"); 

        }

    }


});

谢谢你的帮助。

删除document.ready包装,使makeLink可用于页面的其余部分

    function getText(change){
      if(change == "link") {
      //call jquery function 

        makeLink()

      }
    }


    function makeLink() {
      if ($("#makeALinkModalPopup").is(":hidden")){
        $("#makeALinkModalPopup").fadeIn("slow");

        $("#backgroundPopup").css({  
          "height": document.documentElement.offsetHeight

        });

        $("#backgroundPopup").css({"opacity": "0.7"});
        $("#backgroundPopup").fadeIn("slow"); 

      }
    }

将makeLink移到全局范围并正常调用。 只有JavaScript函数。 您所看到的区别仅是范围。

在此处了解范围。

就像其他人所说的,请取出文档。准备好包装。 您的函数无需在此处定义,因为无法在document.ready之外看到它。

您不应在文档准备事件中定义函数,而应在单独的文件中定义。

然后,您在哪里:

//call jquery function called makeLink()

刚放

makeLink()

您不需要准备好dom。

刚有

function makeLink() {
    if ($("#makeALinkModalPopup").is(":hidden")){
    $("#makeALinkModalPopup").fadeIn("slow");

     $("#backgroundPopup").css({  
        "height": document.documentElement.offsetHeight

      });

    $("#backgroundPopup").css({"opacity": "0.7"});
    $("#backgroundPopup").fadeIn("slow"); 

        }

    }

刚有

function getText(change)
{
   if(change == "link")
   {
      makeLink();

   }

}

如果您想在dom上使用该功能,则需要这样做。

$(document).ready(makeLink); <我在语法上可能是错误的,但是为了安全起见,我知道这是可行的。

$(document.ready(function(){
// do what ever you want
//even call make link

makeLink();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM