内联 onclick JavaScript 变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5586857/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Inline onclick JavaScript variable
提问by Pit Digger
I have a JavaScript above this html is there any way to pass it inside EditBanner(JS Variable Here) in code below ?
我在这个 html 上面有一个 JavaScript 有没有办法在下面的代码中将它传递到 EditBanner(JS Variable Here) 中?
//EditBanner to be changed to pass a Js variable.
<input id="EditBanner" type="button" value="Edit Image" onclick="EditBanner();"/>
回答by Khez
There's an entire practice that says it's a bad idea to have inline functions/styles. Taking into account you already have an ID for your button, consider
有一个完整的实践表明拥有内联函数/样式是一个坏主意。考虑到您已经有按钮的 ID,请考虑
JS
JS
var myvar=15;
function init(){
document.getElementById('EditBanner').onclick=function(){EditBanner(myvar);};
}
window.onload=init;
HTML
HTML
<input id="EditBanner" type="button" value="Edit Image" />
回答by Rocket Hazmat
<script>var myVar = 15;</script>
<input id="EditBanner" type="button" value="Edit Image" onclick="EditBanner(myVar);"/>
回答by Bobby Borszich
Yes, JavaScript variables will exist in the scope they are created.
是的,JavaScript 变量将存在于它们创建的范围内。
var bannerID = 55;
<input id="EditBanner" type="button"
value="Edit Image" onclick="EditBanner(bannerID);"/>
function EditBanner(id) {
//Do something with id
}
If you use event handlers and jQuery it is simple also
如果您使用事件处理程序和 jQuery,它也很简单
$("#EditBanner").click(function() {
EditBanner(bannerID);
});