jQuery - 将元素传递给函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5306449/
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 18:56:34  来源:igfitidea点击:

jQuery - Pass element to function

jqueryfunctionelement

提问by Charlie Sheather

Hi I have a function that i want to pass an element to via clicking the element or calling the function with the element as a paramter. This is what I have:

嗨,我有一个函数,我想通过单击元素或使用元素作为参数调用函数来传递元素。这就是我所拥有的:

function change_btm_cat(item) {
        $('div.prod_matrix').removeClass('block');
        $('div.prod_matrix').addClass('none');
        $('div.prod_matrix#'+item.attr('id')).removeClass('none');
        $('div.prod_matrix#'+item.attr('id')).addClass('block');
        $('div.btm_cat').removeClass('green_grad');
        $('div.btm_cat').addClass('grey_grad');
        item.removeClass('grey_grad');
        item.addClass('green_grad');
        //ps. i know its messy, just testing stuff
    }

I can easily get it to work using this:

我可以使用这个轻松地让它工作:

$('div.btm_cat').click(function() {
        change_btm_cat($(this));
    });

But when i try:

但是当我尝试:

$('another.element').live('click', function() {
   change_btm_cat($('div.btm_cat#7'));
});

It seems to pass nothing to the function.

它似乎没有向函数传递任何内容。

See jsFiddle for working example: http://jsfiddle.net/rb7ZG/1/

有关工作示例,请参见 jsFiddle:http: //jsfiddle.net/rb7ZG/1/

采纳答案by Quintin Robinson

You are going a little overboard with the selector, try this.

你对选择器有点过分了,试试这个。

$('another.element').live('click', function() {
   change_btm_cat($('#7'));
});

Since you have the ID and the ID is pretty much the most refined piece of unique information you can have (being the identifier) there is not need for the other refinements.

由于您拥有 ID 并且 ID 几乎是您可以拥有的最精炼的唯一信息(作为标识符),因此不需要其他精炼。

http://jsfiddle.net/rb7ZG/2/

http://jsfiddle.net/rb7ZG/2/

Let me know if I missed your goal.

如果我错过了你的目标,请告诉我。

回答by Rob

try:

尝试:

$('div.btm_cat').click(change_btm_cat);

function change_btm_cat()
{
     $(this) //becomes available
}

and

$('another.element').live('click', change_btm_cat);