onclick 中的新功能
new function in onclick
编辑:举个例子。我需要 if/else
的支持
我想这样做:
<button onclick="function() {alert('Hi!');prompt('What can I do for you?', 'make a Sandwich');}">Hello World!</button>
显然这不起作用。
你知道我该怎么做吗?
如何"call"一个新功能?
我不能简单地在<script></script>
节点中定义它。
您不需要 function
即可拨打电话。您可以直接使用 Javascript 代码。这被认为是不好的做法。
<button onclick="alert('Hi!'); prompt('What can I do for you?','make a Sandwich');">
Hello World!
</button>
您还可以使用 function
作为事件处理程序,如下所示:
HTML
<button onclick="fnHandler();">
Hello World!
</button>
Javascript
function fnHandler() {
alert('Hi!');
prompt('What can I do for you?','make a Sandwich');
}
使用 addEventListener
你可以绑定来自 javascript 的事件而不是内嵌在 HTML(Recommended):
HTML
<button id="myButton">
Hello World!
</button>
Javascript
document.getElementById('myButton').addEventListener('click', function() {
alert('Hi!');
prompt('What can I do for you?','make a Sandwich');
});
通用功能的更新版本,因为添加监听器增加了点击的唯一性
<button onclick="function_name() id="button">Some Text</button>
现在用js写函数定义
function function_name(){ .... statements; }
将此与 if-else 一起使用的典型示例
<script>
document.getElementById('button').onclick = function() {
if (Calc.Input.value == '' || Calc.Input.value == '0') {
window.alert("Please enter a number");
} else {
document.getElementById('button').value=' Justera längd ';
}
return false;
}
</script>
不建议把函数写在参数里面。最好将它们写在一个单独的函数上,然后 link 使用上面收听的方法之一。您仍然可以通过使用这样的匿名函数来执行您在示例中所说的操作:
<button onclick='(function(){
alert("hello world");
prompt("I am the Doctor","oh yeah");
})()'></button>
编辑:举个例子。我需要 if/else
的支持我想这样做:
<button onclick="function() {alert('Hi!');prompt('What can I do for you?', 'make a Sandwich');}">Hello World!</button>
显然这不起作用。
你知道我该怎么做吗?
如何"call"一个新功能?
我不能简单地在<script></script>
节点中定义它。
您不需要 function
即可拨打电话。您可以直接使用 Javascript 代码。这被认为是不好的做法。
<button onclick="alert('Hi!'); prompt('What can I do for you?','make a Sandwich');">
Hello World!
</button>
您还可以使用 function
作为事件处理程序,如下所示:
HTML
<button onclick="fnHandler();">
Hello World!
</button>
Javascript
function fnHandler() {
alert('Hi!');
prompt('What can I do for you?','make a Sandwich');
}
使用 addEventListener
你可以绑定来自 javascript 的事件而不是内嵌在 HTML(Recommended):
HTML
<button id="myButton">
Hello World!
</button>
Javascript
document.getElementById('myButton').addEventListener('click', function() {
alert('Hi!');
prompt('What can I do for you?','make a Sandwich');
});
通用功能的更新版本,因为添加监听器增加了点击的唯一性
<button onclick="function_name() id="button">Some Text</button>
现在用js写函数定义
function function_name(){ .... statements; }
将此与 if-else 一起使用的典型示例
<script>
document.getElementById('button').onclick = function() {
if (Calc.Input.value == '' || Calc.Input.value == '0') {
window.alert("Please enter a number");
} else {
document.getElementById('button').value=' Justera längd ';
}
return false;
}
</script>
不建议把函数写在参数里面。最好将它们写在一个单独的函数上,然后 link 使用上面收听的方法之一。您仍然可以通过使用这样的匿名函数来执行您在示例中所说的操作:
<button onclick='(function(){
alert("hello world");
prompt("I am the Doctor","oh yeah");
})()'></button>