Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
jQuery:replace()类名/regex_Jquery_Regex - Fatal编程技术网

jQuery:replace()类名/regex

jQuery:replace()类名/regex,jquery,regex,Jquery,Regex,我正在尝试编写jquery的一行,该行查找具有以“a\d”(字母a和数字)开头的类的输入,并用另一个数字替换该数字 这就是我尝试过的,有人注意到为什么这不起作用吗 $('form').find('input[class^="a\d"]').replace(/a\d+/,'a22'); 请注意:这是许多行中的一行,我提取了这行,因为这是我遇到问题的地方。您需要这样做: $('form').find('input[class^="a"]').attr('class', function(i,cls

我正在尝试编写jquery的一行,该行查找具有以“a\d”(字母a和数字)开头的类的输入,并用另一个数字替换该数字

这就是我尝试过的,有人注意到为什么这不起作用吗

$('form').find('input[class^="a\d"]').replace(/a\d+/,'a22');

请注意:这是许多行中的一行,我提取了这行,因为这是我遇到问题的地方。

您需要这样做:

$('form').find('input[class^="a"]').attr('class', function(i,cls) {
    if( /a\d/.test( cls ) ) {
        return cls.replace(/a\d+/,'a22');
    }
});
使用
.attr()
设置
(或任何属性)时,可以向其传递一个具有2个参数的函数。
i
是迭代中的当前索引。
cls
class
的当前值

返回值将用于更新
。如果未返回任何内容,则不会更改任何内容。

尝试此操作

var regExp = /(a\d+)(.*)?/;
$('form').find('input[class^="a"]').each(
    function()
    {
        var el = this;
        var className = el.replace(regExp, "a22$2");
        el.className = className;
    }
);

我不认为“attributestartedwith”选择器适用于正则表达式。文档声明它“选择具有指定属性的元素,该属性的值以给定的字符串开头。”。非常感谢。这很好用。我会经常使用这种方法!