parameter function in jquery -
i want make function parameter. working below code not working. can tell me doing wrong.
<head> <script type="text/javascript" src="jquery-1.7.2.js"></script> <script type="text/javascript"> $(function hide(fn){ $(fn).click(function(){ $('div').hide() }) }) </script> <style> div { width:500px; height:500px; background:#ff0000; } </style> </head> <body> <button onclick="hide(this)">click hide</button> <a href="#">click</a> <button>click</button> <div></div> </body>
one important thing: should write unobtrusive javascript, considered best practice. it, can maintain separation of content code. thus, first step remove onclick
handler on <button>
element.
i'm assuming want click button says "click hide" hide <div>
. okay, let's skeleton code out <script>
:
$(document).ready(function() { $(<button>).click(function() { $(<div>).hide(); }); });
but need somehow link click
handler button, , link hide
function actual div
. here's easiest way this: give <button>
, <div>
ids. let's say...
<button id="hide-button">...</button> <div id="hide-div">...</div>
now, need make few modifications our skeleton code:
$("#hide-button").click(function() { $("#hide-div").hide(); });
here's simple code does. when dom loads, nameless function (you can't name functions define on fly*) invoked document's ready event. nameless function attaches click
handler #hide-button
button, when click button, anonymous function invoked. function calls hide
, jquery magic works in browsers, on #hide-div
div hide it.
*well, can, if define them first , pass them. this:
var fn = function() {...}; $(document).ready(fn);
edit
since asker not want use ids or classes, here's alternative solution:
<script> function hide() { $('div').hide(); } </script> ... <button onclick="hide()">click hide</button> <div></div>
be careful not place function hide()
within jquery's document-ready idiom. doing deny access hide()
because of scoping.
Comments
Post a Comment