问题描述
我想要一个div只调用一个函数(不移动我的位置在页面上),而不是调用我的JavaScript函数 - 它移动我的位置在页面上
我做错了什么? (在joomla内部运行)
为什么我的JavaScript中没有调用我的JavaScript函数?
http://....com/test.php#p3
< div id =p1onclick =testFunction()> ;
< / div>
< div id =p3>部分内容< / div>
< script type =text / javascript>
testFunction();
< / script>
< / div>
< script type =text / javascript>
function testFunction(){
alert(Test);
}
< / script>
这是因为你有两个单独的脚本块,一个调用在第二个定义的函数。
< div id =p1onclick =testFunction() >点击我< / div>
< div id =p3>部分内容< / div>
< script type =text / javascript>
testFunction();
function testFunction(){
alert(Test);
}
< / script>
注释说你需要在顶部定义它们不是真的,请看这里:
他们会是true如果你定义了一个变量函数: var testFunction = function(...
。一般来说,你应该在JS块的顶部定义函数,可读性和可维护性,但这不是你的脚本不工作的原因。
注意:你可以看到onclick工作以及在我给你的例子。 p>
你有一个关于函数提升的教程:
I want a div to just call a function(not move my position on the page) but instead of calling my JavaScript function - it moves my location on the page
what am I doing wrong? (running inside of joomla)
Why is my JavaScript function not being called in my div?
http://....com/test.php#p3
<div id="p1" onclick="testFunction()">
</div>
<div id="p3">Some content</div>
<script type="text/javascript">
testFunction();
</script>
</div>
<script type="text/javascript">
function testFunction() {
alert("Test");
}
</script>
It's because you have two separate script blocks, the first one calling the function defined in the second one. Put them into one single block and it will work.
<div id="p1" onclick="testFunction()">click me</div>
<div id="p3">Some content</div>
<script type="text/javascript">
testFunction();
function testFunction() {
alert("Test");
}
</script>
Comments saying you need to define it at the top are not true, see here: http://jsfiddle.net/xDf5e/
They would be true if you defined a variable function like: var testFunction = function(...
. Generally, you should define functions at the top of your JS blocks, it makes the code more readable and maintanable, but that's not the reason your script is not working.
Note: you can see the onclick works fine as well in the example I gave you.
You have a nice tutorial about function hoisting here: http://elegantcode.com/2011/03/24/basic-javascript-part-12-function-hoisting/
这篇关于为什么我的JavaScript函数不在我的div中调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!