当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - 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 */);
分享给朋友:
您可能感兴趣的文章:
随机阅读: