jQuery selector that simulates :starts-with or :ends-with for searching text?

試著忘記壹切 提交于 2019-11-29 03:48:56

Not by default as far as I know, but you can add your own pseudo-selectors through $.expr[":"]: http://jsfiddle.net/h6KYk/.

$.extend($.expr[":"], {
    "starts-with": function(elem, i, data, set) {
        var text = $.trim($(elem).text()),
            term = data[3];

        // first index is 0
        return text.indexOf(term) === 0;
    },

    "ends-with": function(elem, i, data, set) {
        var text = $.trim($(elem).text()),
            term = data[3];

        // last index is last possible
        return text.lastIndexOf(term) === text.length - term.length;
    }
});

When you don't want to extend jQuery, you can use the filter() function to create the contains functionality:

$("div").find("span").filter(function () {
    return $(this).text().indexOf(text) >= 0;
});

Or create a startsWith function with a regular expression:

var expression = new RegExp('^' + text);
$("div").find("span").filter(function () {
    return expression.test($.trim($(this).text()));
});

The endsWith function is quite similar:

var expression = new RegExp(text + '$');
$("div").find("span").filter(function () {
    return expression.test($.trim($(this).text()));
});

Note the use of $.trim() because HTML can contain a lot of whitespace.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!