简体   繁体   中英

passing a local variable within the function

By clicking on the following DIV, nothing happens. Where is the error ?

<div onclick="function dummy(that) { alert(that.toString())}" class="next">></div>

Please help.

You are defining dummy but not calling it. I don't think it works that way, not in the HTML onclick property anyway.

I suggest you move dummy() into a separate code block:

<script type='text/javascript'>
function dummy(that) { alert(that.toString())}
</script>

and then:

<div onclick="dummy(this);" class="next">></div>

or attach the function programmatically like so:

document.getElementById("myDummyDIV").onclick = function(event) { ..... }

This should do the trick:

<div onclick="dummy(this);" class="next"></div>

<script type="text/javascript">
function dummy(that) {
    alert(that.toString());
}
</script>

This is a function declaration, not invocation.

You could do something like this:

(function dummy(that) { alert(that.toString())}) (event);

and the complete HTML would be:

<div onclick="(function dummy(that) { alert(that.toString())})(event);" class="next">></div>

This is silly actually. The function you've declared is unusable as a function unless you intend to do some more fantastic stuff and call the click event of this link from other methods elsewhere. However, if you're hell-bent-for-leather intent on putting the function declaration in the onclick event, it can be done this way:

<div onclick="(function dummy(that) { alert(that.toString())})();" class="next">></div>

You end up putting the function in it's own block and then the () at the end tells the parser to do it.

你不在这里创建功能你可以写下面的内容

<div onclick="alert(that.toString())" class="next">></div>

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