jQuery function parameters
Ok, so basically I just want to make a simple function that will change the CSS value of开发者_运维百科 a div that has been clicked. The selected div ($(this)) will be passed to the divClicked function. I could just call the CSS jQuery function here but i want to perform the implementation in another function.
$('#container').children().click(function(){
divClicked($(this));
});
but in the divClicked function when i go to run a jQuery function on the div variable it doesn't work... any idea what i'm doing wrong.
function divClicked(selectedDiv)
{
$(selectedDiv).css('background', 'red');
}
Where are you doing the hookup? If it's in a script
tag above the actual "container" div
and you don't have it wrapped in some kind of ready
callback or similar, that might be the problem. Or if you're adding children to the div afterward (since you're using click
, which hooks up the handler only to the children there right then).
Because if the "container" div
and its children already exist, your code works:
HTML:
<div id='container'>
<div>Child 1</div>
<div>Child 2</div>
<div>Child 3</div>
</div>
<input type='button' id='btnAdd' value='Add a new child'>
JavaScript:
$('#btnAdd').click(function() {
$("#container").append("<div>New child, clicking me <em>won't</em> work</div>");
});
$('#container').children().click(function(){
divClicked($(this));
});
function divClicked(selectedDiv)
{
// You don't want `$` here, but I've left it just to demonstrate
// that your code should, largely, be working
$(selectedDiv).css('background', 'red');
}
Live copy
...but note that elements added afterward don't work, because they weren't there when you hooked things up.
Fixing it will depend on what's wrong. It could just be wrapping your hook-up code in a ready
handler (as I have in that example) or moving it to code in a script
tag at the bottom of your page, just before the closing </body>
tag (as the YUI folks recommend), or perhaps using live
or delegate
.
Your code should work. See this. Is there something in your HTML we don't know?
But just as a note, you are already passing a jQuery object when you pass $(this)
. You then wrap it as a jQuery object again. Instead use just selectedDiv
. Alternatively, pass this
and use $(selectedDiv)
.
I think it would work anyway what "justkt" suggested..
Did you try "background-color" for your CSS style !?
use this jquery code for avoid the error. so its unavailable of live activities
$(document).ready(function(e) {
$('#btnAdd').click(function() {
$("#container").append("<div>New child, clicking me <em>won't</em> work</div>");
});
$(document).delegate('#container div', "click", function(){divClicked(this);});
var divClicked=function(selectedDiv) {
$(selectedDiv).css('background', 'red');
};
});
<div id='container'>
<div class="1">Child 1</div>
<div class="2">Child 2</div>
<div class="3">Child 3</div>
</div>
<input type='button' id='btnAdd' value='Add a new child'>
精彩评论