在 jquery 选择器上调用函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10934228/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:59:06  来源:igfitidea点击:

calling function on jquery selector

jquery

提问by geoff swartz

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.

好的,通常我会认为自己是 jquery 的中级用户,但这似乎是一个非常菜鸟的问题,我不太确定如何编码。

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...

我有一个 div,我想针对它运行一个函数。我知道如何做到这一点的唯一方法是......

$("#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?

...但它写出了整个 dom。我只想在这个元素上运行该函数。我怎么做?

采纳答案by thecodeparadox

If you maintain that each element in HTML DOM has unique idthat 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.

如果您认为 HTML DOM 中的每个元素都是唯一的id,这意味着没有两个元素具有相同的id,则$('#divname')始终返回单个元素并且$('#divname').each()将运行一次。不超过一个。

Now in your case you want something like

现在在你的情况下你想要类似的东西

dosomething( $('#divname') );

For example:

例如:

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

 doSomething( $('#divname') );

DEMO

演示

回答by Sampson

You should callthe 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:

由于我们构建和调用的方式doStuff,我们仍然可以使用它作为回调.each

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

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

小提琴:http: //jsfiddle.net/jonathansampson/WuyJc/