jQuery target only elements within parent div

那年仲夏 提交于 2019-12-11 17:16:36

问题


I have a number of widgets on a page and I want to re-use classes throughout. I have a question mark icon that should toggle visibility between 2 divs inside the widget.

The problem is I can't get my code to only target the current widget. I have tried the usual techniques but none seem to be working here.

The fiddle is here, http://jsfiddle.net/clintongreen/9hvVn/

The click function in question works from the question mark icon. The divs that need toggleClass are .widget-content and .widget-content_next

Thanks :)


回答1:


widget-content and widget-content_next aren't direct ancestors of the link, I think you want something like this:

 $(this).closest(".widget").find('.widget-content').toggleClass("hidden");
 $(this).closest(".widget").find(".widget-content_next").toggleClass("hidden");



回答2:


You could use parent in conjunction with siblings

$("a.expand_widget").live("click", function () {
    $(this).parent().siblings(".widget-content").toggleClass("hidden");
    $(this).parent().siblings(".widget-content_next").toggleClass("hidden");
});

http://jsfiddle.net/KKMaW/

or alternatively you could limit the selector to the parent nodes

$("a.expand_widget").live("click", function () {
    var root = this.parentNode.parentNode;
    $(".widget-content",root).toggleClass("hidden");
    $(".widget-content_next",root).toggleClass("hidden");
});



回答3:


I don't think the .closest method works for you because it only finds ancestors, not siblings or descendants of ancestors:

Given a jQuery object that represents a set of DOM elements, the .closest() method searches through these elements and their ancestors in the DOM tree and constructs a new jQuery object from the matching elements. The .parents() and .closest() methods are similar in that they both traverse up the DOM tree.

Solution

Instead of using .closest, you could use the .parent function to find the owner, then use the other tree traversal functions to find the children that match certain selectors.

Try this edited code - http://jsfiddle.net/9hvVn/3/:

$("a.expand_widget").live("click", function () {
    var parentWidget = $(this).parent('div.widget-head')
        .parent('li.widget');
    parentWidget.children(".widget-content").toggleClass("hidden");
    parentWidget.children(".widget-content_next").toggleClass("hidden");
});

It is fairly strict, but you could loosen it up a bit if you needed to. You could also use various sibling functions on the div.widget-head instead of getting the parent-of-parent first.



来源:https://stackoverflow.com/questions/8527483/jquery-target-only-elements-within-parent-div

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!