在JavaScript函数中调用JQuery函数
我得到了这个JQuery代码: 文件:code.js在JavaScript函数中调用JQuery函数,javascript,jquery,html,Javascript,Jquery,Html,我得到了这个JQuery代码: 文件:code.js jQuery(function(){ function renderSVG(){ //Something }; }); 文件:index.html <script> function mostrarOdonto() { renderSVG(); }; </script> 函数mostrarodono(){ r
jQuery(function(){
function renderSVG(){
//Something
};
});
文件:index.html
<script>
function mostrarOdonto() {
renderSVG();
};
</script>
函数mostrarodono(){
renderSVG();
};
但我有个问题:
在mostrarodono()内的renderSVG()中
“未捕获引用错误:未定义renderSvg”
我尝试了$renderSVG();但是不起作用。有人能帮我吗
非常感谢
PD:抱歉,英语不好函数
renderSVG()
是一个本地函数,因为它在jQuery(function(){}
中。它仅在该范围内有效,因此无法通过其他范围访问。因此请像这样尝试
<script>
jQuery(function(){
function mostrarOdonto() {
renderSVG();
};
};
</script>
jQuery(函数(){
函数mostrarodono(){
renderSVG();
};
};
你可以这样做
HTML:
<input type="button" value="go" onclick=" mostrarOdonto();">
这应该可以根据您的要求工作。Jquery部分可以进入您的Code.js文件。这是由javascript闭包引起的。它在Jquery调用中是本地的,在外部是不可访问的。您可以在此处阅读有关它的更多信息: 您可以在jQuery函数调用之外声明对象,使其全局可用。例如:
function RenderSVG(){
//Do Stuff
}
jQuery(function(){
RenderSVG();
});
这确保了它可以在jquery范围之外访问
或者,如果您在jQuery中真的需要它,您可以使用jQuery插件a la:
例如:
(function( $ ) {
$.fn.renderSVG = function( options ) {
//Do Stuff with canvas since it would be referenced in this.
};
}( jQuery ));
然后您可以这样称呼它:$('#mycanvas').renderSVG({/*options*/});
更新1:
您必须确保在加载jQuery和任何插件后何时调用代码。
在您的
标记中
您应该将
或任何您的jquery文件调用
然后是任何插件脚本…src=“jquery.svg.js”
,然后将代码放入:
<script>
function RenderSVG(){
}
//And most important is that you call it after it is ready. In this example
//I use jQuery(window).load you can also use jQuery(document).ready
jQuery(window).load(function(){
RenderSVG();
});
</script>
函数RenderSVG(){
}
//最重要的是在它准备好后调用它
//我使用jQuery(窗口)。加载您也可以使用jQuery(文档)。准备好了吗
jQuery(window).load(函数(){
RenderSVG();
});
如果它仍然不起作用,您必须确保svg方法的库没有做任何奇怪的事情。为了确保我们必须知道您正在使用的库。我认为这可以帮助您简单明了地使用它
$(document).ready(function() {
mostrarOdonto();
});
function renderSVG() {
alert("Testing purpose only");
};
function mostrarOdonto() {
renderSVG();
};
或者将renderSVG声明为jQuery之外的变量。但问题是,从那一刻起,该变量将是全局变量。声明全局变量不是一个好做法。@请解释为什么声明全局变量不是一个好做法。您好,但它不起作用,sayd:Uncaught ReferenceError:jQuery未定义在最后一行中,need“}”);“但是我的renderSVG是一个函数:function renderSVG(){//code};请看我的问题,谢谢。如果你想让renderSVG成为一个Java脚本函数,函数应该在调用范围内。或者像上面那样,或者从jquery范围调用它-
jquery(function(){function mostrarodon(){renderSVG();};}”;
我的renderSVG函数使用JQuery方法,并在此处显示错误:clear()方法谢谢
$(document).ready(function() {
mostrarOdonto();
});
function renderSVG() {
alert("Testing purpose only");
};
function mostrarOdonto() {
renderSVG();
};