简体   繁体   中英

calling function on jquery selector

Okay, normally I would consider myself an intermediate user of jquery, but this seems like a very noob issue that I'm not quite sure how to code.

I have one div that I want to run a function against. The only way I'm aware of how to do this is something like...

$("#divname").each(function(){
  dostuff();
});

This seems like a bit more work when I know there will only be one element. I tried this...

$("#divname", function(){ 
  console.log($(this));
});

... but it writes out the whole dom. I just want to run the function on this one element. How do I do that?

You should call the function, passing your element in as its object:

function doStuff() {
    alert( $(this).html() );
}

doStuff.call( $("#foo")[0] );

Due to the way we built and call doStuff , we can still use it as a callback on .each :

$(".bar").each( doStuff );

Fiddle: http://jsfiddle.net/jonathansampson/WuyJc/

If you maintain that each element in HTML DOM has unique id that means no two elements have same id , then $('#divname') always return a single element and $('#divname').each() will run one time. not more than one.

Now in your case you want something like

dosomething( $('#divname') );

For example:

function doSomething( el ) {
   el.append('<span>hello</span>');
}

 doSomething( $('#divname') );

DEMO

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