12 javascript jquery
如何从javascript调用jQuery函数?
//jquery
$(function() {
function my_fun(){
/.. some operations ../
}
});
//just js
function js_fun () {
my_fun(); //== call jquery function
}
Run Code Online (Sandbox Code Playgroud)
Eld*_*rov 16
你不能.
function(){
function my_fun(){
/.. some operations ../
}
}
Run Code Online (Sandbox Code Playgroud)
这是一个关闭.my_fun()仅在该匿名函数内部定义.只有my_fun()在正确的范围级别(即全局)声明它时,才能调用.
$(function () {/* something */})是一个IIFE,意味着它在DOM准备好后立即执行.通过my_fun()在匿名函数内部声明,可以防止脚本的其余部分"看到"它.
当然,如果要在DOM完全加载时运行此函数,则应执行以下操作:
function my_fun(){
/* some operations */
}
$(function(){
my_fun(); //run my_fun() ondomready
});
// just js
function js_fun(){
my_fun(); //== call my_fun() again
}
Run Code Online (Sandbox Code Playgroud)
小智 15
是的,你可以(这是我理解原始问题的方式).我就是这样做的.只需将其与外部环境联系起来.例如:
//javascript
my_function = null;
//jquery
$(function() {
function my_fun(){
/.. some operations ../
}
my_function = my_fun;
})
//just js
function js_fun () {
my_function(); //== call jquery function - just Reference is globally defined not function itself
}
Run Code Online (Sandbox Code Playgroud)
我在尝试访问对象的方法时遇到了同样的问题,该方法仅在DOM对象就绪时实例化.作品.我的例子:
MyControl.prototype = {
init: function {
// init something
}
update: function () {
// something useful, like updating the list items of control or etc.
}
}
MyCtrl = null;
// create jquery plug-in
$.fn.aControl = function () {
var control = new MyControl(this);
control.init();
MyCtrl = control; // here is the trick
return control;
}
Run Code Online (Sandbox Code Playgroud)
现在你可以使用简单的东西:
function() = {
MyCtrl.update(); // yes!
}
Run Code Online (Sandbox Code Playgroud)
小智 11
var jqueryFunction;
$().ready(function(){
//jQuery function
jqueryFunction = function( _msg )
{
alert( _msg );
}
})
//javascript function
function jsFunction()
{
//Invoke jQuery Function
jqueryFunction("Call from js to jQuery");
}
Run Code Online (Sandbox Code Playgroud)
http://www.designscripting.com/2012/08/call-jquery-function-from-javascript/
小智 5
<script>
// Instantiate your javascript function
niceJavascriptRoutine = null;
// Begin jQuery
$(document).ready(function() {
// Your jQuery function
function niceJqueryRoutine() {
// some code
}
// Point the javascript function to the jQuery function
niceJavaScriptRoutine = niceJueryRoutine;
});
</script>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
111725 次 |
| 最近记录: |