开发者

Abstract question about Dom Object as Value Object in Javascript

I've got an image gallery where each item in the gallery has a unique ID I'm using to tie it to my backend so that I can run DB actions etc. I'm using the data attribute to hold the 'imageid' on the parent div of each image for example: data-imageid="168"

The image gallery items have alot of nested divs so on rollover/click I find myself doing alot of the below in order to run actions:

$(this).parent().parent().attr('data-imageid');

It doesn't feel like a clean solution or the best performance wise. How are other people handling this? What's the best solution? Whatever the solution, this must be a problem solved everyday.

Ed开发者_如何学编程it: I realize my subject line is vague but it further explains where my heads at with this problem.


You can specify a criterion to go "up to", so if you want to go up to the nearest div or li or whatever, either use jQuery's .closest() or a simple upTo() function:

function upTo(el, tagName) {
  tagName = tagName.toLowerCase();
  var el;
  do {
    el = el.parentNode;
    if (el && el.tagName && el.tagName.toLowerCase() == tagName) {
      return el;
    }
  } while (el)
}


This sounds suspiciously like you have a case of divitis. In any case you can use .parents([selector]) with a filter to make your code a bit less verbose. e.g.

$(this).parents(".classOfDivContainingData").attr('data-imageid');

or you could loop through the parent divs on initial load, and copy the data attribute to the "this" in your example. Is there a reason why you can't set the attribute here in the first place?


You can try this

$(this).parents("[data-imageid]:first");


I would recommend you to use additional attributes to the elements:

<div data-imageid="367">
    <div>
        <div data-parent-imageid="367">
        </div>
    </div>
</div>

So you can make action knowing only the element which fired the event. Using this solution you don't care about structure of the elements, move them in the DOM tree freely and performance will be improved too.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜