捕获在jQuery回调函数中匹配的类

问题描述 投票:1回答:2

我正在尝试访问回调函数中由jQuery选择器匹配的类。例如,如果我有以下HTML,

<p class="someclass sorted-1 anotherclass">test</p>

我想匹配这个元素并获得sorted-1类名。值1是任意的。像下面这样的东西。 getMatchedClass()是伪代码。我以为我可以从$(this)获得价值,但我没有看到它。

$('[class*=sorted-]').on('click', function() {
    var className = getMatchedClass();
    console.log(className); // should output 'sorted-1'
});

有谁知道这是否可能?我很难想出搜索条件。我不断得到选定值的结果,这不是我想要的。

谢谢

更新

基于@maheer-ali的回答,我提出了以下解决方案。

   $(function() {
        function column(className) {
            const regex = /sorted-([0-9]+)/;
            return className.match(regex)[0].replace(regex, '$1');
        }
        $('[class*=sorted-]').each(function(i, r) {
            // col is the dashed number after sorted
            // if parsing `sorted-42`, `col` would equal 42
            const col = column($(r).context.className);

            // Use the `col` value here.
            $(r).doSomething({ column: col });
        });
    });
javascript jquery jquery-selectors
2个回答
3
投票

你可以使用match()和正则表达式。并获得结果数组的第一个元素。

$('[class*=sorted-]').on('click', function() {
    var className = this.className.match(/sorted-[0-9]+/)[0];
    console.log(className); // should output 'sorted-1'
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="someclass sorted-1 anotherclass">test</p>

另一种方法是使用split()startsWith()split() className" "并使用find()获取startsWith元素元素字符串"sorted-"

$('[class*=sorted-]').on('click', function() {
    var className = this.className.split(' ').find(x => x.startsWith('sorted-'))
    console.log(className); // should output 'sorted-1'
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="someclass sorted-1 anotherclass">test</p>

1
投票

您传递的回调函数将使用触发它的事件进行调用。

您可以访问event.target.classList以获取该对象上所有类的数组。如果您正在寻找一组固定的类模式,则可以搜索该类的列表。

希望这有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.