【问题标题】:jQuery: Get class with number and replace itjQuery:用数字获取类并替换它
【发布时间】:2012-04-05 22:04:07
【问题描述】:

鉴于此 HTML:

<div id="foo">
    <input type=button class="foo abtn_1">
    <input type=button class="joe bbtn_2">
    <input type=button class="doe cbtn_2">
    <input type=button class="cool dbtn_1">
</div>

当我单击一个按钮时,我需要获取包含下划线的类(仅)并将其编号从 2 更改为 1。

目前我在每个班级都使用这个:

$('.abtn_1').live('click', function () {
 $(this).switchClass('abtn_1','abtn_2');
});
$('.abtn_2').live('click', function () {
 $(this).switchClass('abtn_2','abtn_1');
});
$('.bbtn_1').live('click', function () {
 $(this).switchClass('bbtn_1','bbtn_2');
});
$('.bbtn_2').live('click', function () {
 $(this).switchClass('bbtn_2','bbtn_1');
});
// etc

因此,我没有多次这样做,而是想通过获取下划线类并相应地更改它的数字来将整个事情变成一两行。

我想它会是这样的:

var a =      // $(this).attr('class') without number and underscore
var b =      // This class number only
var c = $(this).attr('class'); // If I wanted to call it from 
                               // its parent $('#foo input'). 

if a contains number 1 {
    $(this).switchClass(c, a + '_1')
} else {
    $(this).switchClass(c, a + '_2')
};

【问题讨论】:

  • 您可以使用正则表达式来获取数字,或者只包含最后一个字符的子字符串。顺便说一句: .live() 已弃用。我不知道您使用的是哪个 jQuery 版本,但从 1.7 开始,您应该使用 .on() 而不是 .live()
  • 我的客户想要使用不存在的 jQuery 1.6。虽然那不是我的问题。至于正则表达式,我知道我需要做什么。我只是想不通,否则我会问。谢谢

标签: jquery class replace switch-statement


【解决方案1】:

此代码将执行以下操作:

  1. 对所有输入元素使用一个事件处理程序
  2. 将已弃用的.live() 替换为.delegate()(因为OP 使用jQuery 1.6)
  3. 无论aaa_1bbb_2 类名在类名列表中的哪个位置,都可以找到它

代码如下:

​$(document).delegate('#foo input', 'click', ​function() {
    if (this.className.match(/_1(\s|$)/)) {
        this.className = this.className.replace("_1", "_2");
    } else {
        this.className = this.className.replace("_2", "_1");
    }
});​

当使用.delegate().on() 时,您应该为主jQuery 对象选择器选择一个静态父元素。我在这里使用 document 只是因为您没有透露 HTML 的其余部分,但最好使用更接近实际目标元素的内容。


这是另一种使用自定义替换功能的有趣方法:

$(document).delegate('#foo input', 'click', function() {
    this.className = this.className.replace(/_(\d)(\s|$)/, function(str, p1, p2) {
        return("_" + (p1 == "1" ? "2" : "1") + p2);
    });
});​

在这里演示:http://jsfiddle.net/jfriend00/xgUzT/

【讨论】:

  • 我相信,.on() 它不在 jQuery 1.6 上 :)
  • 如果你还在使用 jQuery 1.7 之前的版本,那么你应该使用.delegate() 而不是.live().live() 已被所有版本的 jQuery 弃用。
  • 完美运行。不幸的是,我的客户使用 jQuery 1.6,所以我必须坚持使用 live()。但是,我没有使用任何一个,因为这将在一个函数中。谢谢
  • 嘿,我不是说你错了,只是他说他用的是1.6
  • @Nicosunshine - 好的,我看到 1.6 信息已添加到评论中。这不是我在写答案时看到的问题。无论如何,.delegate() 推荐用于 1.6。 .live() 可能会导致文档对象上的事件处理程序过多导致性能问题。 .delegate().on() 都允许您选择更接近目标对象的静态父元素,以防止 .live() 导致的性能瓶颈。
【解决方案2】:
$(document).delegate('#foo input', 'click', function () {
    var currentClass = this.className, //you can use $(this).attr("class") here if you want
    slicedClass = currentClass.slice(0,-2); //I'm asuming the _number is always at the end and with one digit, for better slicing use .replace(/_[0-9]+/, "");

   if(currentClass.search("_1") !== -1) {
       $(this).switchClass(currentClass, slicedClass + '_2');
   } else {
      $(this).switchClass(currentClass, slicedClass + '_1');
   }

});

告诉我这是否适合你。

编辑 这是您在评论中提供的小提琴的工作版本,请对它进行所需的更改http://jsfiddle.net/uFLsx :)

【讨论】:

  • 哦,有一件事,您可以在正则表达式中添加 $ 以仅在末尾匹配,例如:.replace(/(_[0-9]+)$/, "");
  • 我似乎收到了这个错误:Uncaught TypeError: Cannot call method 'slice' of undefined which from the 3rd line, slice(0,-2)
  • 好的,className 未定义,尝试console.log("Value of this", this);console.log("Value of the class", this.className); 在控制台中查看值
  • 好的,我发现了错误。它不能将 (this) 传递给函数。这是我的代码:jsfiddle.net/XWtSx
  • @jQuerybeast 最后一个,这是一个工作版本,做你需要的更改jsfiddle.net/uFLsx
【解决方案3】:

使用这样的东西:

$('#foo input').live('click', function () {
    var from_class = "";
    var to_class = "";

    $.each($(this).attr('class').split(/\s+/),function(i,c){
        var matches = c.match(/(\w+_)(\d)/i);               
        if(matches != null)
        {
            from_class = matches[0];
            from_number = matches[2];
            to_number = (matches[2] == '1')?'2':'1';
            to_class = matches[1]+to_number;
            return false;   // Stop the loop since we found the class.
        }
    });
    if(from_class != "" && to_class != "")
    {
        $(this).switchClass(from_class,to_class);
    }
});

就像 Johannes Klauß 所说,如果您使用的是新版本的 jQuery,请使用 .on() 而不是 .live()。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多