define function in javascript onbuttonclick
Hi How can I define a function on button click in HTML, I tried something like that:
<input type="button" value="sth" onclick="
<script type="text/javascript">
function hello()(
window.print();
var z =document.GetElementById('ogog');
z.inneHTML="hello";
<script>
">
I have to define my function here because I have code which generate me a site in which's header i can not define javascript function and I want one function on button click. this is only an example. This is the way it 开发者_开发问答should look like?
You can attach a script to a button by putting a string representation of that script in the onclick handler:
<input type="button" onclick="window.alert('Hi!')">
This code will be executed when the button is clicked. In general, the script tag is used to define scripts that can be referenced elsewhere in the HTML document, while strings containing JavaScript code are used in the body of the document to actually execute that code.
Assuming you realy want to define a new funciton on your onclick event you can try this:
<input type="button" value="something" onclick="window.hello=function(){window.print();var z =document.GetElementById('ogog');z.innerHTML='hello';}">
You don't have to open the script tags, you just need to write directly the code you need.
You'd better include it inside a function defined in the head section, though:
<head>
<script type="text/javascript">
function hello () { ... }
</script>
</head>
<body>
<input type="button" onclick="hello()" />
</body>
or, even better, load it from an external .js file:
<script type="text/javascript" src="scripts.js"></script>
You might want to try:
<script type="text/javascript">
function hello() {
window.print();
var z =document.GetElementById('ogog');
z.inneHTML="hello";
}
</script>
<input type="button" value="sth" onclick="hello()"/>
You will have to define the script tag in the same file first, also '{' for function definitions -
<script type="text/javascript">
function hello() {
window.print();
var z =document.GetElementById('ogog');
z.inneHTML="hello";
}
</script>
Then call the function with its name -
<input type="button" value="sth" onclick="hello()"/>
Check this link for more details.
You can also put code directly, as for example a jQuery call, as for example onclick="$('#confirmation_modal').modal();"
to open a modal or onclick="$('#confirmation_modal').modal('toggle');"
to close it.
Or also you can define a function and call it after.
yyesThis code will be executed when the button is clicked. In general, the script tag is used to define scripts that can be referenced elsewhere in the HTML document, while strings containing JavaScript code are used in the body of the document to actually execute that code.
精彩评论