将元素ID传递给Javascript函数 [英] Pass element ID to Javascript function
问题描述
这里是HTML代码:
< button id =button1class =MetroBtnonClick =myFunc(this.id);> Btn1< / button>
< button id =button2class =MetroBtnonClick =myFunc(this.id);> Btn2< / button>
< button id =button3class =MetroBtnonClick =myFunc(this.id);> Btn3< / button>
< button id =button4class =MetroBtnonClick =myFunc(this.id);> Btn4< / button>
一个非常简单的JS函数在这里:
function myFunc(id){
alert(id);
你可以在 JsFiddle 。
问题是:
我不知道,也许不会将 this.id
传递给 myFunc
函数,否则会出现其他问题。
有什么问题?
任何帮助都不胜感激。
在jsFiddle中,默认情况下,您键入到脚本块中的代码被包装在window.onload上执行的函数中:
< script type ='text / javascript'> //<![CDATA [
window.onload = function(){
function myFunc (id){
alert(id);
}
}
//]]>
< / script>
因此,您的函数 myFunc
是不在全局范围内,因此不可用于您的html按钮。通过将选项更改为< code>在< head> 中禁止包装,因为Sergio暗示您的代码未被包装:
< script type ='text / javascript'> //<![CDATA [
function myFunc(id){
alert(id);
}
//]]>
< / script>
,所以这个函数在全局范围内并且可以用于你的html按钮。
I have seen many threads related to my question title.
Here is HTML Codes :
<button id="button1" class="MetroBtn" onClick="myFunc(this.id);">Btn1</button>
<button id="button2" class="MetroBtn" onClick="myFunc(this.id);">Btn2</button>
<button id="button3" class="MetroBtn" onClick="myFunc(this.id);">Btn3</button>
<button id="button4" class="MetroBtn" onClick="myFunc(this.id);">Btn4</button>
And a very simple JS function is here :
function myFunc(id){
alert(id);
}
You can see in JsFiddle.
The problem is :
I have no idea, maybe doesn't pass this.id
to myFunc
function, or some problem else.
What's the problem ?
Any help would be appreciated.
In jsFiddle by default the code you type into the script block is wrapped in a function executed on window.onload:
<script type='text/javascript'>//<![CDATA[
window.onload = function () {
function myFunc(id){
alert(id);
}
}
//]]>
</script>
Because of this, your function myFunc
is not in the global scope so is not available to your html buttons. By changing the option to No-wrap in <head>
as Sergio suggests your code isn't wrapped:
<script type='text/javascript'>//<![CDATA[
function myFunc(id){
alert(id);
}
//]]>
</script>
and so the function is in the global scope and available to your html buttons.
这篇关于将元素ID传递给Javascript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!