javascript 如何从html调用javascript函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13705445/
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
How to call javascript function from html
提问by Mohit Verma
How we can call start() javascript function for this case from HTML
对于这种情况,我们如何从 HTML 调用 start() javascript 函数
(function() {
var never, start;
never = function() {
return alert("try");
};
start = function() {
return alert("try harder");
};
}).call(this);
My HTML
我的 HTML
<input type="button" value="press" onclick="never()" ></input>
回答by I Hate Lazy
When you assign event handler code to attributes, any functions that are used need to be available in the global variable scope.
将事件处理程序代码分配给属性时,使用的任何函数都需要在全局变量范围内可用。
To accomplish this, you can make them properties of window
. Currently, your never
and start
functions are local to the IIFE function scope.
要做到这一点,您可以将它们设为window
. 目前,您的never
和start
函数在 IIFE 函数范围内是本地的。
// IIFE function
(function() {
// var never, start; // local variables
// Make the functions globally scoped
window.never = function() {
return alert("try");
};
window.start = function() {
return alert("try harder");
};
}).call(this);
You can expose a single namespace if you prefer
如果您愿意,可以公开单个命名空间
// IIFE function
(function() {
var ns = window.ns = {};
// Make the functions globally scoped
ns.never = function() {
return alert("try");
};
ns.start = function() {
return alert("try harder");
};
}).call(this);
And then change your inline handler to use ns.never();
and ns.start();
.
然后将您的内联处理程序更改为使用ns.never();
和ns.start();
。
回答by chubbsondubs
First give your input tag an id:
首先给你的输入标签一个id:
<input id="someInputField" type="button" ... />
Next register a callback on it by executing code when the document is ready:
接下来通过在文档准备好时执行代码来注册一个回调:
$(document).ready( function() {
// define a function called never
function never() {
alert( 'Never say never');
}
// register a function on the click event handler of that input tag:
$('#someInputField').click( never );
});
回答by Peter Richmond
You may find it easier to use a javascript library like jQuery. Using that library you can do this:
您可能会发现使用像 jQuery 这样的 javascript 库更容易。使用该库,您可以执行以下操作:
<script type="text/javascript">
$(document).ready(function() {
var count = 0
$("#tryme").click(function () {
if (count == 0) {
alert('try');
count++
}
else if (count == 1) {
alert('try harder');
}
});
});
</script>
<input type="button" value="press" id="tryme" ></input>