代码之家  ›  专栏  ›  技术社区  ›  Dycey

在jquery中基于css类设置变量

  •  0
  • Dycey  · 技术社区  · 15 年前

    仍在尝试找出惯用的jquery——这里有一些jquery用于在DIV类的基础上设置变量——有没有一种jquery方法可以更紧凑地完成这项工作,因为所讨论的DIV可能有多个类……

    var currentType = 'component';
    // text_component, image_component, tagged_component
    if ($(my_div).hasClass('.text_component'))   { currentType = 'text_component' };
    if ($(my_div).hasClass('.image_component'))  { currentType = 'image_component' };
    if ($(my_div).hasClass('.tagged_component')) { currentType = 'tagged_component' };  
    
    var dialog_box = $('div[id^='+currentType+'_dialog]');
    
    3 回复  |  直到 11 年前
        1
  •  1
  •   Sinan    15 年前

    如果我告诉你正确的话,我建议你使用 metadata plugin 它是由jquery的创建者john resig编写的,您可以在任何DIV元素上设置任何数据,以供以后使用。您不需要从CSS类中获取参数。您可以随时读取该数据。

    示例标记:(来自插件页)

    <div class="someclass {some: 'data'} anotherclass">...</div>
    

    然后在javascript中:

    var data = $('div.someclass').metadata();
    if ( data.some == 'data' ) alert('It Worked!');
    

    希望能有所帮助,西南。

        2
  •  2
  •   Andreas Grech    15 年前
    currentType = $(my_div).attr("class");
    

    它将分配类属性中的任何内容,从而处理多个类

    如果以后您可能想进行个别检查,您可以将类拆分为一个单独的类值数组…例如:

    var classes = currentType.split(' '); //return an array of separate class values
    
        3
  •  0
  •   Blixt    15 年前

    测试时使用 hasClass ,不包括 . (点)

    至于一个更简单的方法,你可以缩短它,但是使用 哈斯级 可能是最好的方法。

    我假设这些类具有优先权(所以后面的类在 if 如果有多个类,优先于其他类?还是要支持多个“组件”?

    这里有一个更有效的版本,可以更好地显示正在发生的事情:

    var currentType, div = $(my_div);
    // text_component, image_component, tagged_component
    if (div.hasClass('tagged_component')) currentType = 'tagged_component';
    else if (div.hasClass('image_component')) currentType = 'image_component';
    else if (div.hasClass('text_component')) currentType = 'text_component';
    else currentType = 'component';
    
    var dialog_box = $('div[id^='+currentType+'_dialog]');