This might be simple to someone, but I am a bit of a novice and searched everywhere. I have a javascript function.
mkfile : function(fm) {
I am trying to execute this from an on click comm开发者_开发知识库and.
Any ideas. Sorry Im a bit of a dunce in this, but I have tried everything and nothing happens.
Use the attribute onclick
as follows: <a onclick="javascript:mkfile()" >Bob</a>
. You don't have to have the javascript:
before-hand but it helps in browsers like IE (don't even get me started).
By the way, your code is wrong, it should be
function mkfile(fm) {
// your code
}
Don't hesistate to ask if you don't understand this.
Without more code it is difficult to tell what you are doing wrong, but normally it goes like this:
<button id="foo">Click me!</button>
<script type="text/javascript">
document.getElementById('foo').onclick = function() {
alert('Hello World!');
}
</script>
DEMO
There are several ways of binding event handlers. I suggest to read quirksmode.org - Introduction to Events , MDC - Event handlers and MDC - The DOM and JavaScript and also follow the links given there ;)
As others have noted, it's not really possible to see what is wrong with your code without seeing more of it. But the small portion you posted (with its name:value
) is valid only in a couple of circumstances, both of which are somewhat common patterns of JS design:
// Pattern one
var makeMyObject = function() {
var privateVar = 'a private member';
var privateMethod = function() {};
var objOut = {
mkDir:function() {/*more code*/},
mkFile:function() {/*more code*/},
delFile:function() {/*more code*/}
};
return objOut;
};
myObject = makeMyObject();
myObject.mkFile();
// Pattern two
var myObject = {
mkDir:function() {/*more code*/},
mkFile:function() {/*more code*/},
delFile:function() {/*more code*/}
};
myObject.mkFile();
If this is what you have, the way you can bind this to an onclick in your HTML code is:
<a href="/some_page.html" onclick="myObject.mkFile()">Click here</a>
Or in your JS,
domMyAnchorElement.onclick = myObject.mkFile; // Note there are no parens because you are binding the function, not invoking it.
精彩评论