简体   繁体   中英

How to pass argument if event handler is assigned in initialization function?

It is always good to separate presentation layer and behaviour between HTML and Javascript based on head first book.

They tell me not to do:

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

But instead, do below:

The example below separate the behaviour from HTML code (structure).

<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>

This allows HTML (structure) to look clean and "behaviour" part is initialized in init() function when page loads. I understand that so far.

But then I wonder how am I supposed to pass an argument to showAlert() function???

Below does not work, it will call the showAlert() as soon as the page loads and this is not what I want to because it needs to be fired onclick.

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

Is it possible to pass arguments to showAlert() function but still separate the behaviour and structure?

UPDATE

Forgot to mention.. I'm using prototype.

Wrap your code in a function.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM