简体   繁体   中英

jQuery run function in context of element

I have some function that (for example only) looks for all divs and appends to them.

function test() {
    $('div').append(/*...*/);
}

Now I'm loading new divs via $.get function to my container element. After loading of new divs I want to call test() function in contex (limited to) my container element. I only want to append sth to new divs. I dan't want to append twice to old divs.

I don't want to edit test function if it is possible.

function test(container) {
    $(container).find('div').append(/*...*/);
}

used like:

test("body");
test("#mainContainer");
test("ul.spiffy > li");

In short, you simply pass in the selector that you want to modify divs inside.

If you want to allow for a "default" value, you can do something like this:

function test(container) {
    if (container == undefined) container = "body";
    $(container).find('div').append(/*...*/);
}

Now, if you pass no parameter to test, it will apply the append to all div elements inside of body .

$('div', 'container').append(/* code */);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM