1

I have a series of photos on a page, which have below them some text information and some buttons:

<div class="photowrapper">
 <div class="photowrapperphoto">
  <div class="photocontainer">image</div>
  </div>
 <div class="textwrapperphoto">
  <div class="textleftwrapperphoto">
   <div class="phototitle">photo_0001</div>
   <div class="photoprice">&pound;3.00</div>
   <div class="photosize">6 by 4 inch</div>
 </div>
 <div class="textrightwrapperphoto">
  <div class="photoaddbutton">Add</div>
  <div class="photoremovebutton">Delete</div>
 </div>
</div>

I want to put in some jquery so that when someone clicks on the 'photoaddbutton', it amends the class of 'photowrapperphoto' (to add a background color).

I can't seem to figure out how to identify the element photowrapperphoto.

I have loads of the above html (i.e. loads of images) on the page. I just want the immediately preceeding 'photowrapperphoto' to change, but at the moment the jquery I'm using changes all 'photowrapperphoto' classes on the page.

$(document).ready(function() {
 $('.photoaddbutton').click(function() {
  $('.photowrapperphoto').attr('class', 'photowrapperphotoselected');
 });
});

Any ideas?

4

2 回答 2

1

I'd recommend you let the photowrapperphoto items keep their photowrapperphoto class, and add an additional class selected, instead of changing the class.

The javascript to modify the correct photowrapperphoto could be:

$(document).ready(function() {
    $('.photoaddbutton').click(function() {
        $(this)
            .closest('.photowrapper')   // go up in the DOM until .photowrapper
            .children('.photowrapperphoto') // go down one level to .photowrapperphoto 
            .addClass('selected');
    });
});

To specify a special style for the selected photowrapperphoto, you can use a rule like this in your CSS:

.photowrapperphoto.selected
{
    background-color: red;
}
于 2013-03-30T00:11:53.430 回答
0
$(document).ready(function() {
   $('.photoaddbutton').click(function() {
      $(this).closest('.photowrapper').find('.photowrapperphoto').prop('class', 'photowrapperphotoselected');
   });
});

但我建议添加和删除一个类,而不是一个一个替换。第一个类标记元素的通用角色,第二个标记它在出现时的附加角色。

于 2013-03-30T00:09:27.717 回答