0

can you call a javascript function on event handlers? What I mean is like,

... onClick="dosomething()">
<script type="text/javascript">
function dosomething(){alert("I just did something");}

the code isn't complete but i've tried it this way all nice and neat and it doesn't work, does this mean we have to enter the whole JS code inside the event handler???

4

2 回答 2

1

您可以附加事件处理程序而无需内联指定它。如果您知道元素的 id,它非常简单。

Javascript

function doSomething(){
   alert("I just did something");
}

var elem = document.getElementById("idGoesHere");
elem.onclick = function(){
    doSomething();
}

HTML

<div id="idGoesHere">Click Me</div>

JS 小提琴:http: //jsfiddle.net/DYqjA/

于 2013-08-21T23:53:09.097 回答
1
<script>
document.getElementById("myBtn").onclick=function(){dosomething()};
function dosomething(){alert("I just did something");}
</script>

使用 JavaScript 的粗略示例

于 2013-08-21T23:53:15.850 回答