如果在初始化函数中分配了事件处理程序,如何传递参数?

时间:2010-09-24 07:01:53

标签: javascript html prototypejs structure

基于头一读,将HTML和Javascript之间的表示层和行为分开总是好的。

他们告诉我不要这样做:

<textarea onclick="showAlert()"></textarea>

但是,请执行以下操作:

以下示例将行为与HTML代码(结构)分开。

<html>
<head>

<script type="text/javascript">
window.onload = init;

function init() {
  $('txt_area').onclick = showAlert;
}

function showAlert(say) {
  alert(say);
}
</script>
</head>
<body>
<textarea id="txt_area"></textarea>
</body>
</html>

这允许HTML(结构)看起来干净,并且在页面加载时在init()函数中初始化“behavior”部分。到目前为止我明白了。

但后来我想知道我该如何将一个参数传递给showAlert()函数???

下面不起作用,它会在页面加载后立即调用showAlert(),这不是我想要的,因为它需要在onclick上激活。

function init() {
  $('txt_area').onclick = showAlert("hello");
}

是否可以将参数传递给showAlert()函数但仍然将行为和结构分开?

更新

忘了提..我正在使用原型。

1 个答案:

答案 0 :(得分:3)

将代码包装在函数中。

$('txt_area').onclick = function() {
    showAlert("hello");
};
相关问题