jQuery - Traversing the DOM
Here is my HTML:
<li>
<div class=开发者_如何学Go"menu_inner">
<a href="#">
<div class="button"><img class="486" src="images/portalbutton.png" /></div>
<div class="prod_description"> </div>
</a>
</div>
</li>
I want to add a .click() function to .prod_description, the click event should take the background colour applied in CSS from the li element.
Using this code:
$(".prod_description").mousedown(function() {
$('#toolbar').css('background-color', $(this).parent().css('background-color'))
})
I dont seem to be able to get the correct $(this).parent()
combination....
You can do that like this:
$(".prod_description").mousedown(function() {
$('#toolbar').css('background-color', $(this).closest('li').css('background-color'))
});
.parent()
gets the immediate parent, you want to go up a few levels (<a>
, <div>
, <li>
). .closest('li')
climbs the parents and gets the first one that's an <li>
. In this case, .parent('li')
would also work :)
In javascript, you must use backgroundColor
, not background-color
.
Update: As it turns out, jQuery is able to handle both formats, and even the DOM API itself let you do something like this: obj.style.setProperty('background-color', 'red');
Use click event instead of mousedown. Use closest to get the li
element
$("div.prod_description").click(function() {
$('#toolbar').css('background-color', $(this).closest('li').css('background-color'))
});
I have used a tag selector also in the click event. If you can give the background color in a CSS class, then you can use something like this
li.mybg { background-color: #a9a9a9; }
<li class="mybg">
<div class="menu_inner">
<a href="#">
<div class="button">
<img class="486" src="images/portalbutton.png" />
</div>
<div class="prod_description"> </div>
</a>
</div>
</li>
$("div.prod_description").click(function() {
$('#toolbar').addClass('mybg');
});
精彩评论