简体   繁体   English

将jQuery代码应用于多个类

[英]applying jquery code to more than one class

I have this little snippet of code applied to only one class 我将这小段代码仅应用于一个类

function replaceSF(foo,bar)
{
j$('.labelCol').children().each(function(){ 
    console.log('i am on children each for labelCol');
    console.log('foo: '+foo);
    console.log('bar: '+bar);
    console.log('jsthis.text: '+j$(this).text());
    if(j$(this).text() == foo)
    {      
        j$(this).html(''+bar);    
    }
    else if(j$(this).text().trim().replace('\*','').replace('\n','') == foo)
    {
        j$(this).html(j$(this).html().replace(foo,''+bar));
    }
    });  
    j$('.labelCol').each(function(){   
    if(j$(this).text() == foo )
    {      
        j$(this).html(''+bar);   
    }
    }); 
}

but I need to use this code for like 10 classes. 但是我需要将此代码用于10个类。 What's the best approach to do this? 最好的方法是什么? I was trying to rewrite this function as replaceSF(className,foo,bar) but I didn't get any results. 我试图将此函数重写为replaceSF(className,foo,bar)但没有得到任何结果。

Thanks. 谢谢。

You can modify your selector to something like: 您可以将选择器修改为:

j$('.labelCol, .labelCol2, .labelCol3, .labelCol4, .labelColn').children().each(function(){ 

... ...

添加更多如下所示的类

j$('.labelCol,.anotherclassname,.anotherclassname1').children().each(function(){

To write the function as you say you'd like, you could take the approach: 要按照您的意愿编写函数,可以采用以下方法:

function replaceSF(arrayOfClassNames,foo,bar){
    j$('.' + arrayOfClassNames.join(', .')).children() /* and so on… */

    /* which would form the CSS-style selector:
    j$('.labelCol, .secondClassName, .anotherClassName').children()
    */
}

Calling the function as: 将该函数调用为:

replaceSF(['labelCol','secondClassName', 'anotherClassName'], 'foo', 'bar');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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